Wednesday, January 5, 2011

nth-child CSS trick with IE Fix

The :nth-child() and :nth-of-type() pseudo-classes allows you to select elements with a formula.
The syntax is :nth-child(xn+y), where you replace x and y by numbers of your choice. For instance, :nth-child(3n+1) selects the 1st, 4th, 7th etc. child.

for example:

ul li:nth-child(3n+3) {
  color: #ccc;

select every third list item inside unordered lists. That is, the 3rd, 6th, 9th, 12th, etc. nth-child accepts two keywords: even and odd."Even" selects even numbered elements, like the 2nd, 4th, 6th, etc. "Odd" selects odd numbered elements, like 1st, 3rd, 5th, etc.

The trick is understanding the "n" and algebraic equation that represents. Think of "n" as starting at zero and then a set of all positive integers. Then complete the equation. So the 3n is "3xn", and the whole equation together is "(3xn)+3". Now substituting in the zero and positive integers, we get:
(3 x 0) + 3 = 3 = 3rd Element
(3 x 1) + 3 = 6 = 6th Element
(3 x 2) + 3 = 9 = 9th Element
How about the :nth-child(2n+1)?
(2 x 0) + 1 = 1 = 1st Element
(2 x 1) + 1 = 3 = 3rd Element
(2 x 2) + 1 = 5 = 5th Element

Example : ( With IE Fix)

<!--[if lt IE 7]>
<script src=""></script>
<!--[if lt IE 8]>
<script src=""></script>
<!--[if lt IE 9]>
<script src=""></script>

border:1px solid #ccc;

list-style-type: none;

ul li:nth-child(2n+2) {

If you want to download IE7-js you can download from here :  Click here



Shardul Singh said...

Thanks for pointing out... now IE8 it supports.

Shardul Singh said...

Post updated!! Thank you guys you are simply awesome.

Please let me know if anything needs to be updated.

Mani Raja said...

Thank You so much! It is really helpful. Now my lists are showing same result as other modern browsers.

Vitor Neves said...

Does't work at least with IE8

Shardul Singh said...

Hi Vitor , Why dont you copy HTML ( Yellow ) part and create a new HTML file and test with your browser.. I've tested it with IE 7 , IE8 & IE8+ its working BTW.

Melvin said...

Wow! This is great I am looking for something that will make IE8 support the nth-child pseudo class selector and now I found it thanks to you sir.

Anonymous said...

What about IE 10 & 11? Can't we figure out a way to eliminate IE from the planet so we don't have to keep coming up with workarounds?

melbourne web designer said...

Your blog has given me that thing which I never expect to get from all over the websites. Nice post guys!

Shardul Singh said...

This works on IE-v11 also give a try. Happy coding

Post a Comment