我想知道如何选择一行中的最后一项。我知道第 n 个选择器是选择最后一项,例如连续的最后 3 项:
.post-entry:nth-last-child(-n+3) { margin-bottom: 0; }
但这不符合我的需求。如果最后一行末尾有 3 个元素,它会很好用,但是当最后只有 2 个帖子时,它就不起作用了。
当你在上面的例子中删除一个元素时,布局就乱七八糟了:
我想知道的是如何选择最后一行中的最后一项,而不会像上图那样弄乱我的布局。此外,如果只剩下两个或一个元素。
.post {
margin-bottom: 30px;
padding-bottom: 20px;
border-bottom: 3px solid red;
}
.post img {
width: 100%;
}
.post:nth-last-child(-n+3) {
margin-bottom: 0;
border: none;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="col-md-4 post"><img src="http://placehold.it/300x200"></div>
<div class="col-md-4 post"><img src="http://placehold.it/300x200"></div>
<div class="col-md-4 post"><img src="http://placehold.it/300x200"></div>
<div class="col-md-4 post"><img src="http://placehold.it/300x200"></div>
<div class="col-md-4 post"><img src="http://placehold.it/300x200"></div>
<div class="col-md-4 post"><img src="http://placehold.it/300x200"></div>
<div class="col-md-4 post"><img src="http://placehold.it/300x200"></div>
<div class="col-md-4 post"><img src="http://placehold.it/300x200"></div>
<div class="col-md-4 post"><img src="http://placehold.it/300x200"></div>
</div>
最佳答案
在您的情况下,使用 nth-child 很难根据需要设置 css。我认为,仅使用 CSS 是不可能的。
我尝试过叠加模式。这不是个好主意,但对你来说很好。它很简单,适用于所有响应式布局和 n 个元素。
检查结果: click me for 9 items和 click me for 8 items
Click me to check in responsive layout
.container{ position: relative;}
.post {
margin-bottom: 30px;
padding-bottom: 20px;
border-bottom: 3px solid red;
}
.post img { width:100%; }
#overlay-div{
background-color: white;
height: 40px;
width: 100%;
bottom: 0;
position: absolute;
}
<div class="container">
<div class="col-md-4 post"><img src="http://placehold.it/300x200"></div>
<div class="col-md-4 post"><img src="http://placehold.it/300x200"></div>
<div class="col-md-4 post"><img src="http://placehold.it/300x200"></div>
<div class="col-md-4 post"><img src="http://placehold.it/300x200"></div>
<div class="col-md-4 post"><img src="http://placehold.it/300x200"></div>
<div class="col-md-4 post"><img src="http://placehold.it/300x200"></div>
<div class="col-md-4 post"><img src="http://placehold.it/300x200"></div>
<div class="col-md-4 post"><img src="http://placehold.it/300x200"></div>
<div class="col-md-4 post"><img src="http://placehold.it/300x200"></div>
<div id="overlay-div"></div> <!-- this div hide last line of border -->
</div>
[编辑]
我找到了另一种方法,
http://keithclark.co.uk/articles/targeting-first-and-last-rows-in-css-grid-layouts/
演示:codepen.io
关于html - 如何只选择最后一行的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38029002/