Is it possible to select, say, every fourth element in a set of elements?
Ex: I have 16 <div>
elements... I could write something like.
div:nth-child(4),
div:nth-child(8),
div:nth-child(12),
div:nth-child(16)
is there a better way to do this?
This question is related to
css
css-selectors
Try this
div:nth-child(4n+4)
You need the correct argument for the nth-child
pseudo class.
The argument should be in the form of an + b
to match every ath child starting from b.
Both a
and b
are optional integers and both can be zero or negative.
a
is zero then there is no "every ath child" clause.a
is negative then matching is done backwards starting from b
.b
is zero or negative then it is possible to write equivalent expression using positive b
e.g. 4n+0
is same as 4n+4
. Likewise 4n-1
is same as 4n+3
.Examples:
li:nth-child(4n) {_x000D_
background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
</ol>
_x000D_
li:nth-child(4n+1) {_x000D_
background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
</ol>
_x000D_
/* two selectors are required */_x000D_
li:nth-child(4n+3),_x000D_
li:nth-child(4n+4) {_x000D_
background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
</ol>
_x000D_
/* when a is negative then matching is done backwards */_x000D_
li:nth-child(-n+4) {_x000D_
background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
</ol>
_x000D_
div:nth-child(4n+4)
Source: Stackoverflow.com