Css :nth-child

CSS :nth-child(an+b) pseudo class represent all sibling elements whose sibling position (starting from 1) is obtained by putting n=0,1,2,3… and so on. Note that sibling can be of any type but should have same parent container element.

:nth-child values

valueDescription
:nth-child(2n+1)Every 1st, 3rd, 5th, ... sibling element
:nth-child(odd)Every odd sibling element (same as 2n+1)
:nth-child(2n+2)Every 2nd, 4th, 6th, ... sibling element
:nth-child(even)Every even sibling element (same as 2n+2)
:nth-child(5)Fifth sibling
:nth-child(-n+6)represents the 6 first sibling elements

Example of :nth-child

Change background of every alternate (2,4,6…) sibling

<style type="text/css" media="screen">
.box > :nth-child(2n+2) {
  background-color:lightgreen;
}
</style>
<div class="box">
  <div>div1</div>
  <p>p1</p>
  <p>p2</p>
  <p>p3</p>
  <p>p4</p>
  <div>div2</div>
  <p>p5</p>
  <p>p6</p>
</div>
refresh

Related

Specification

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments