David Anderson
David Anderson

Reputation: 65

Is it possible to draw vertical separators in the interior gaps of a CSS grid of varying columns?

I want to have a responsive grid of elements of variable length. The grid should fill the available width of the containing element, with the number of columns varying depending on the width of the container. This is straightforward to achieve using CSS grids; however, I don't know how to add a vertical border between columns (i.e., only in the interior column gaps). The below simple demo manages to achieve a vertical border in the event that there are three columns:

https://codepen.io/yowzadave/pen/OYPvLd?editors=1100

html, body {
  box-sizing: border-box
}

.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(24rem, 1fr));
  grid-column-gap: 0.5rem;
}

.item {
  border-right: 1px solid black;
  padding-right: 0.5rem;
}

.item:nth-child(3n) {
  border-right: none;
  padding-right: 0;
}

.box {
  background-color: pink;
  height: 2rem;
  margin: 0.5rem;
}
<html>
  <body>
    <div class="container">
      <div class="item"><div class="box"></div></div>
      <div class="item"><div class="box"></div></div>
      <div class="item"><div class="box"></div></div>
      <div class="item"><div class="box"></div></div>
      <div class="item"><div class="box"></div></div>
      <div class="item"><div class="box"></div></div>
    </div>
  </body>
</html>

...but in the event that the browser is wider or narrower, the borders will be misplaced. Is there a way to correctly place the borders at all browser widths?

Upvotes: 5

Views: 4024

Answers (1)

Temani Afif
Temani Afif

Reputation: 272734

You can use pseudo element on all the grid item where you will simply have overlap and be sure to cover all the gaps:

html,
body {
  margin: 0;
}

.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr));
  grid-column-gap: 0.5rem;
  overflow:hidden; /* Hide the overflow */
  position:relative;
}

.item {
  box-sizing: border-box;
  position:relative;
}

.item:before {
  content:"";
  position:absolute;
  top:0;
  right:-0.25rem; /* Half the gap */
  height:100vh; /* Big height*/
  width:1px;
  background:#000;
}

.box {
  background-color: pink;
  height: 2rem;
  margin: 0.5rem;
}
<div class="container">
  <div class="item">
    <div class="box"></div>
  </div>
  <div class="item">
    <div class="box"></div>
  </div>
  <div class="item">
    <div class="box"></div>
  </div>
  <div class="item">
    <div class="box"></div>
  </div>
  <div class="item">
    <div class="box"></div>
  </div>
  <div class="item">
    <div class="box"></div>
  </div>
</div>

Upvotes: 3

Related Questions