有没有办法在弹性排列中选择每行的最后一项(没有 JavaScript)?在下面的示例中,我想要一个选择 div 5 和 10(最终是 12)的 CSS 选择器。
当然,它必须是响应式的。
:nth-child(5)
这样的解决方案不会在调整窗口大小时选择正确的 div。我已经仔细阅读了这个问题,它很相似,只是他要选择最后一行的项目。在这里,我想选择每行的最后一项。
既然上面的问题没有合适的解决方案,恐怕没有JavaScript我想做的事是不可能的。
这里是一个 JSFidle 用于生成上面的图像。
#container {
background-color: LightSteelBlue;
width: 100%;
height: fit-content;
flex-wrap: wrap;
display: flex;
justify-content: space-between;
/*justify-content: stretch;*/
}
.child {
font-family: 'Monoton', cursive;
color: white;
font-size: 40px;
display : flex;
align-items : center;
justify-content: center;
width: 100px;
height: 100px;
margin: 10px;
background-color: SteelBlue;
border: 1px solid black;
flex-grow: 1;
}
#container::after {
/*background-color: red;*/
content: "";
flex-grow: 100;
}
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Gajraj+One&family=Monoton&family=Righteous&display=swap" rel="stylesheet">
<div id="container">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
<div class="child">4</div>
<div class="child">5</div>
<div class="child">6</div>
<div class="child">7</div>
<div class="child">8</div>
<div class="child">9</div>
<div class="child">10</div>
<div class="child">11</div>
<div class="child">12</div>
</div>
你可以运行这样的东西:
.wrapper {
display: flex;
flex-wrap: wrap;
}
.item {
width: calc((100% - 2*10px)/5);
height: 50px;
margin-right: 10px;
margin-bottom: 10px;
padding: 5px;
box-sizing: border-box;
}
// last item of each row
.elem:nth-child(5n) {
margin-right: 0;
}
// last 3 items
.elem:nth-last-child(-n+5){
margin-bottom: 0;
}
在此示例中,您可以将 5nth 替换为您想要指定每行元素数量的任何内容。