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

我的梦境 提交于 2020-07-22 21:36:59

问题


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?


回答1:


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>


来源:https://stackoverflow.com/questions/56012789/is-it-possible-to-draw-vertical-separators-in-the-interior-gaps-of-a-css-grid-of

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!