Search code examples
htmlcsscss-tablescss-grid

Horizontal border across entire row of CSS GRID


I need to use a grid layout but also need a horizontal line separating each row.

The only thing I've been able to find is applying a border to each cell, but this only works if there are enough cells to fill each row.

.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 100px);
}

.box {
  border-bottom: 2px solid #ffa94d;
  padding: 1em;
}
<div class="wrapper">
  <div class="box">One</div>
  <div class="box">Two</div>
  <div class="box">Three</div>
  <div class="box">Four</div>
</div>

Is there a way to fix the above so that the entire row has a border?


Solution

  • Add a grid-gap equal to the width of your border then consider gradient to achieve this:

    .wrapper {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      grid-template-rows: repeat(3, 100px);
      grid-row-gap:2px;
      background:
        repeating-linear-gradient(to bottom,
          #0000 0 100px, #ffa94d 0 102px /*+2px here*/
        );
    }
    
    .box {
      padding: 1em;
    }
    <div class="wrapper">
      <div class="box">One</div>
      <div class="box">Two</div>
      <div class="box">Three</div>
      <div class="box">Four</div>
    </div>

    Another idea is to consider a pseudo-element that you add to the 1st,4th,7th .. (3n + 1)th element:

    .wrapper {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      grid-template-rows: repeat(3, 100px);
      overflow:hidden;
    }
    
    .box {
      position:relative;
      padding: 1em;
    }
    .box:nth-child(3n + 1)::after {
      content:"";
      position:absolute;
      bottom:0px;
      left:0;
      width:100vw;
      height:2px;
      background:#ffa94d;
    }
    <div class="wrapper">
      <div class="box">One</div>
      <div class="box">Two</div>
      <div class="box">Three</div>
      <div class="box">Four</div>
    </div>