Reputation: 8963
I have an overview of item
s, which are built up like this:
<div class="item">...</div>
<div class="item">...</div>
<div class="item lastinrow">...</div>
<div class="item">...</div>
<div class="item">...</div>
<div class="item lastinrow">...</div>
I want to target the first item
-class and every item
-class every time a lastinrow
-class has passed. Is this possible? Or should I just use :nth-child(#)
?
If using :nth-child
is the solution, what number(s) should I use instead of the # if I want to target the first one and every 4th one?
Upvotes: 1
Views: 1679
Reputation: 272106
This selects all .item
elements that are either the first child or immediately follow a .lastinrow
item:
.item:first-child,
.lastinrow + .item {
}
For the sake of completeness, if you want to select every .item
element which is the 3rd child starting from 1 you would write:
.item:nth-child(3n + 1) {
}
.item:first-child,
.lastinrow + .item {
background: #FC0;
}
.item:nth-child(3n + 1) {
color: #F00;
}
<div class="item">First item</div>
<div class="item">...</div>
<div class="item lastinrow">...</div>
<div class="item">Item following last-in-row</div>
<div class="item">...</div>
<div class="item lastinrow">...</div>
Upvotes: 6
Reputation: 128791
You can use the adjacent sibling combinator (+
) to select the next element. You can then combine this with :first-child
to select the first .item
element.
.lastinrow + .item,
.item:first-child {
background: tomato;
color: #fff;
}
<div class="item">...</div>
<div class="item">...</div>
<div class="item lastinrow">...</div>
<div class="item">...</div>
<div class="item">...</div>
<div class="item lastinrow">...</div>
If you want to target every 3rd element (your question says 4th, but I guess you mean 3rd...), you can use 3n + 1
in your nth-child
selector:
.item:nth-child(3n + 1) {
background: tomato;
color: #fff;
}
<div class="item">...</div>
<div class="item">...</div>
<div class="item lastinrow">...</div>
<div class="item">...</div>
<div class="item">...</div>
<div class="item lastinrow">...</div>
<div class="item">...</div>
<div class="item">...</div>
<div class="item lastinrow">...</div>
If you do actually want to select every 4th element, you'd use 4n + 1
instead.
Upvotes: 3