Pages

View Pages:

:nth-child and :nth-of-type

:nth-child{}
CSS:
.div1 p:nth-child(2){
   color:#ff0000;
}

:nth-child(2) = select a color for every p element that is the second child of its parent class .div1

HTML:
<div class="div1">
  <p>Lorem ipsum</p>
  <p>Lorem ipsum</p>
  <p>Lorem ipsum</p>
</div>

OUTPUT:
css
now if we insert <h2> tag above the the first paragraph:
<div class="div1">
  <h2>heading</h2>
  <p>Lorem ipsum</p>
  <p>Lorem ipsum</p>
  <p>Lorem ipsum</p>
</div>

OUTPUT:
css
> because the :nth-child selector apply in the second element of the class .div1

:nth-of-type{}
CSS:
.div1 p:nth-of-type(2){  
  color:#ff0000;
}

:nth-of-type(2) = select the second paragraph child of a parent.

HTML:
<div class="div1">
  <p>Lorem ipsum</p>
  <p>Lorem ipsum</p>
  <p>Lorem ipsum</p>
</div>

OUTPUT:
css
now insert again <h2> tag above the the first paragraph:
<div class="div1">
  <h2>heading</h2>
  <p>Lorem ipsum</p>
  <p>Lorem ipsum</p>
  <p>Lorem ipsum</p>
</div>

OUTPUT:
css
> because the :nth-of-type strictly target the second element in your css declaration unlike the nth-child.

for me its ok to use :nth-of-type instead of :nth-child because its less conditional. 

You can also use :nth-child and :nth-of-type via jquery.

No comments:

Post a Comment