cocacrave cocacrave - 4 months ago 14
HTML Question

SCSS nth-child grid layout

I'm having trouble with this.
I have a bootstrap 3 site with html like this:

<div class="item-container">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="item">
</div>
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="item">
</div>
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="item">
</div>
// and so on...
</div>
</div>


I'd like to make it so that the last "row" (not bootstrap row) of
col
's get
margin-bottom: 0


When device is
xs
screen size:

.item-container {
.row {
.col-xs-12.col-sm-6.col-md-4 {
margin-bottom: 20px;
@media screen and (max-width: $xs-max) {
&:last-child {
margin-bottom: 0;
}
}
}
}
}


When device is
sm
screen size:

.item-container {
.row {
.col-xs-12.col-sm-6.col-md-4 {
margin-bottom: 20px;
@media screen and (max-width: $xs-max) {
&:last-child,
&:nth-last-child(2):nth-child(odd) {
margin-bottom: 0;
}
}
}
}
}


That worked fine selecting the last "row".
However, I'm having trouble with the three column rows. Trying to select the last row.

I've made a jsfiddle: https://jsfiddle.net/rx03nan6/

I'm trying to select the red boxes.

<hr />
is just a break line to show you different types of layout it can have depending on the number of boxes.
<br />
please ignore the br tag, I just wanted the show you how it looks like, so please don't look into the HTML in the jsfiddle.

Answer

So you need to style only the items on the last row, where each row contains 3 items.

You can't simply select the last 3 items with :nth-last-child(-n + 3) because let's say you have 4 items - that would select items 2,3,4 - when we only want to select item 4.

So we need additional logic here:

1) We always select the last item

2) We only want to select the second last item if it item (3n + 2) - 2,5,8,etc.

3) We only want to select the third last item if it item (3n + 1) - 1,4,7,etc.

Your selector will look something like this:

li:nth-child(3n + 1):nth-last-child(-n + 3),
li:nth-child(3n + 2):nth-last-child(-n + 2),
li:last-child {
  border-color: blue;
}

Here's a Codepen demo

Here's an updated fiddle