skip to Main Content

Is there an easy way to draw a diagonal line through a div? The line should go from the top left to bottom right.

.container {
  width: 100%;
  height: 100%;
}
<div class="container">
  <div class="line"></div>
</div>

enter image description here

3

Answers


  1. Use a gradient

    .container {
      width: 200px;
      height: 100px;
      background: linear-gradient(to bottom left,#0000 49%,red ,#0000 51%);
      border: 1px solid;
    }
    <div class="container">
    </div>
    Login or Signup to reply.
  2. You can simply use a linear gradient.

    .container {
      border: 2px solid black;
    }
    
    .strike-through {
      background-image: linear-gradient(to bottom left, #fff 0%, #fff 49.5%, #f00 49.5%, #f00 50.5%, #fff 50.5%, #fff 100%);
    }
    <div class="container strike-through" style="height: 200px; width: 300px;"></div>
    <div class="container strike-through" style="height: 100px; width: 400px;"></div>
    <div class="container strike-through" style="height: 200px; width: 200px;"></div>
    Login or Signup to reply.
  3. you can also use the rotate function (need to calculate the length of diagonal (.line here) with Pythagore)

    .container{
        position: relative;
        width: 500px;
        height: 500px;
        border: 1px solid black;
    }
    
    .line{
        position: absolute;
        top: 0;
        left: 0;
        background: black;
        height: 2px;
        width: 707px;
        transform: rotate(45deg);
        transform-origin: 0%;
    }
    <div class="container">
        <div class="line"></div>
      </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search