CSS nth-child, nth-last-child, first-child, last-child pseudo class selectors (:nth-child()
, :nth-last-child()
, :first-child
, :last-child
) are pretty powerful css selectors to create very useful styles in html.
Here are some points to note about these pseudo classes.
- These pseudo classes can apply to any element like “div”, li, tr, etc.
- In case one uses expression like :nth-child(3n+1), it is calculated for n=0,1,2,3,… and so on. Whatever is the outcome of expression, the style applies to child at that count. e.g. (3n+1) will apply to
Value of n Applies to which child 0 1 1 4 2 7 … … - :nth-last-child() is similar to :nth-child() except that it starts backward from last child.
- These selectors work in most modern browsers (don’t work in IE 8 or older browsers)
:nth-child() odd/even example
This is probably most frequently use case. To have different style for odd/even child, the following example style can be used.
<style type="text/css"> .oddeven > div:nth-child(odd) {background:lightgreen;} .oddeven > div:nth-child(even) {background:lightgray;} </style> <div class="oddeven"> <div>v1</div> <div>v2<div>v2.1</div><div>v2.2</div></div> <div>v3</div> <div>v4</div> </div>
First child (:nth-child(1) or :first-child) example
We can use :nth-child(1) or :first-child (without brackets)
<style type="text/css"> .foo > li:nth-child(1) {background:lightgreen;} .bar > li:first-child {background:lightgray;} </style> First list<ul class="foo"> <li>v1</li> <li>v2</li> <li>v3</li> <li>v4</li> </ul> Second list<ul class="bar"> <li>v1</li> <li>v2</li> <li>v3</li> <li>v4</li> </ul>
:nth-child() first 2 children example
We can use :nth-child(-n+2). Here for n=0,1,2,3, … expression (“-n+2”) value will be 2, 1, 0, -1, …. Hence it will match with first and 2nd child. Zero and negative values are ignored.
<style type="text/css"> .foo > li:nth-child(-n+2) {background:lightgreen;} </style> <ul class="foo"> <li>v1</li> <li>v2</li> <li>v3</li> <li>v4</li> </ul>
Last child (:nth-last-child(1) or :last-child) example
We can use :nth-last-child(1) or last-child (without brackets). :nth-last-child() cound from last element.
<style type="text/css"> .foo > li:nth-last-child(1) {background:lightgreen;} .bar > li:last-child {background:lightgreen;} </style> First list<ul class="foo"> <li>v1</li> <li>v2</li> <li>v3</li> <li>v4</li> </ul> Second list<ul class="bar"> <li>v1</li> <li>v2</li> <li>v3</li> <li>v4</li> </ul>
:nth-child() every third child example
We can use nth-child(3n+1) for every third child starting from first.
<style type="text/css"> .foo > li:nth-child(3n+1) {background:lightgreen;} </style> <ul class="foo"> <li>v1</li> <li>v2</li> <li>v3</li> <li>v4</li> <li>v5</li> </ul>