我想要一个可变长度元素的响应式网格。网格应填充包含元素的可用宽度,并且列数取决于容器的宽度。使用CSS网格很容易实现。但是,我不知道如何在列之间添加垂直边框(即,仅在内部列间隙中)。下面的简单演示在出现三列的情况下设法实现了垂直边框:
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>
...但是在浏览器更宽或更窄的情况下,边框会放错位置。有没有办法在所有浏览器宽度上正确放置边框?
答案 0 :(得分:1)
您可以在所有只会重叠的网格项目上使用伪元素,并确保覆盖所有间隙:
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>