Use CSS to draw diagonal line across of square

Reading Time: < 1 minute

Loading

  1. Create two divs and convert them into flexboxes.
.square {
   position: relative;
   width: 130px;
   height: 130px;
   border: 1px solid black;
   background: red;

   display: flex;
   justify-content: center;
   align-items: center;
}

<div class="square left-diag"></div>
<div class="square right-diag"></div>

2. Add .left-diag:after pseudo element to draw a black dialog line that draws from bottom left to upper right. Sass style is shown below:

.square {
   &.left-diag:after {
     content: "";
     position: absolute;
     z-index: 1;
     border: 1px solid black;
     height: 140%;
     transform: rotate(-45deg);
   }
}

3. Add .right-diag:after pseudo element to draw a black dialog line that draws from bottom right to upper left. Sass style is shown below:

.square {
   &.right-diag:after {
     content: "";
     position: absolute;
     z-index: 1;
     border: 1px solid black;
     height: 140%;
     transform: rotate(45deg);
   }
}

4. Lets refactor the sass styles and group common css properties in a mixin function

@mixin strikethroughDiagonal($rotation) {
  content: "";
  position: absolute;
  z-index: 1;
  border: 1px solid black;
  height: 140%;
  transform: rotate($rotation);
}

.square {
   &.left-diag:after {
     @include strikethroughDiagonal(-45deg); 
   }

   &.right-diag:after {
     @include strikethroughDiagonal(45deg); 
   }
}

Stackblitz repo:

https://stackblitz.com/edit/js-4s7qhi