Saturday, January 24, 2015

CSS3 Selector - nth-of-type

The :nth-of-type(n) selector matches every element that is the nth child, of a particular type, of its parent (from w3schools at http://www.w3schools.com/cssref/sel_nth-of-type.asp).
So assume you have the following HTML:
<ul class="clearfix">
  <li><a href="#bg1">content1</a></li>
  <li><a href="#bg2">content2</a></li>
  <li><a href="#bg3">content3</a></li>
</ul>
And you want to add something after each 'a', you should write style as follow:
li:nth-of-type(1) a::after{
  background: url(sbg1.jpg) no-repeat center;
}
li:nth-of-type(2) a::after{
  background: url(sbg2.jpg) no-repeat center;
}
li:nth-of-type(3) a::after{
  background: url(sbg3.jpg) no-repeat center;
}
The following will not work:
a:nth-of-type(1)::after{
  background: url(sbg1.jpg) no-repeat center;
}
a:nth-of-type(2)::after{
  background: url(sbg2.jpg) no-repeat center;
}
a:nth-of-type(3)::after{
  background: url(sbg3.jpg) no-repeat center;
}
This is because those 'a' elements have different parents.


Create a Successful Online Store at Bigcommerce! Try it Free Now!

No comments:

Post a Comment