CSS diagonal lines - how to fit into its parent element?


How can I make a diagonal line fill in and fit into a box (just pure css - without any use of background image)?

div.diagonal-container {
    border: 1px solid #000;
    width:400px;
    height:400px;
    margin: 0 auto;
}

.to-right,
.to-left {
    border-top:1px solid #ff00ff;
    width:100%;

    -moz-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);
}

.to-right {
    -moz-transform: rotate(-45deg);
    -o-transform: rotate(-45deg);
    -webkit-transform: rotate(-45deg);
    -ms-transform: rotate(-45deg);
    transform: rotate(-45deg);
}
<div class="diagonal-container" style="">
    <div class="to-right"></div>
</div>

<div class="diagonal-container" style="">
    <div class="to-right"></div>
</div>

<div class="diagonal-container" style="">
    <div class="to-left"></div>
</div>

Result:

enter image description here

jsfiddle.

Also, is it possible to have an element only without wrapping it? For instance:

<div class="to-right"></div>
<div class="to-right"></div>
<div class="to-left"></div>

Is it possible?


Answers:


You can draw the lines with pseudo elements.

.diagonal-container {
  border: 1px solid #000;
  width: 400px;
  height: 400px;
  margin: 0 auto;
  position: relative;
  overflow: hidden;
}

.diagonal-container:before {
  border-top: 1px solid #ff00ff;
  content: '';
  position: absolute;
  top: 0; left: 0; right: -50%;
  transform: rotate(45deg);
  transform-origin: 0 0;
}

.to-right:before {
  right: 0; left: -50%;
  transform: rotate(-45deg);
  transform-origin: 100% 0;
}
<div class="diagonal-container to-right">
</div>

<div class="diagonal-container to-left">
</div>

<div class="diagonal-container to-right">
</div>