Css :nth-child and :nth-of-type pseudo classes look very similar initially. But these are slightly different. Few points to explain the difference:
- :nth-child considers all sibling dom elements for counting (irrespective of type). e.g. if
p
has siblingsdiv
,span
,p
, etc.,:nth-child
onp
will consider its all siblings when counting. - :nth-of-type considers sibling dom elements of only same type for counting. e.g. if
p
has siblingsdiv
,span
,p
, etc.,:nth-of-type
onp
will only considerp
siblings when counting.
Example of :nth-child
Using :nth-child change background p
element if it is at 2nd position in all its siblings.
<style type="text/css" media="screen"> .foo > p:nth-child(2) { background-color:lightgreen; } </style> <div class="foo"> <div>div1</div> <p>p1</p> <p>p2</p> <p>p3</p> <div><p>in_div_p1</p><p>in_div_p2</p></div> </div>
Few points to note:
- Here the :nth-child pseudo class style applies to all
p
direct child elements of div of class foo. - The counting is done considering all dom siblings of any type in the container
- Since we used direct child selector using (
.foo > p:nth-child(2)
) nested<p>
elements are unaffected. For more information you can see CSS – direct child vs any descendant selector.
Example of :nth-of-type
Using :nth-of-type change background p
element if it is at 2nd position in its p
siblings.
<style type="text/css" media="screen"> .bar > p:nth-of-type(2) { background-color:lightgreen; } </style> <div class="bar"> <div>div1</div> <p>p1</p> <p>p2</p> <p>p3</p> <div><p>in_div_p1</p><p>in_div_p2</p></div> </div>
Few points to note:
- Here also the :nth-of-type pseudo class style applies to all p direct child elements of div of class foo.
- The counting is done considering only dom siblings of
p
type in the container. - Since we used direct child selector using (
.foo > p:nth-child(2)
) nested<p>
elements are unaffected. For more information you can see CSS – direct child vs any descendant selector.