Caspert Caspert - 5 months ago 7
HTML Question

How to select only items in the last row?

I was wondering how I can select the last items in a row. I know the nth selector is to select the last items, for example the last 3 items in a row:

.post-entry:nth-last-child(-n+3) { margin-bottom: 0; }


But this doesn't meet my needs. It works great if there are 3 items at the end of the last row, but when there are just 2 last posts, it isn't working.

When you delete one item in the above example, the layout is messed up:

enter image description here

What I would like to know is how to select the last item(s) in the last row without messing up my layout like the image above. Also, if there are only two or maybe one items left.



.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>





Here is my Codepen: http://codepen.io/anon/pen/aZpqbK

Answer

Your layout is built on a Bootstrap framework and is adjusting based on Bootstrap media queries.

So to keep it simple and efficient, just manage the bottom border in each existing media query.

Something like this (using breakpoints from your Bootstrap code):

@media (min-width: 768px) {
  .post:nth-last-child { margin-bottom: 0; border: none; }
}

@media (min-width: 992px) {
  .post:nth-last-child(-n+2) { margin-bottom: 0; border: none; }
}

@media (min-width: 1200px) {
   .post:nth-last-child(-n+3) { margin-bottom: 0; border: none; }
}
Comments