The
The syntax is :nth-child()
and :nth-of-type()
pseudo-classes allows you to select elements with a formula.: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
etc.
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
etc.
Example : ( With IE Fix)
<head>
<!--[if lt IE 7]>
<script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE7.js"></script>
<![endif]-->
<!--[if lt IE 8]>
<script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE8.js"></script>
<![endif]-->
<!--[if lt IE 9]>
<script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE9.js"></script>
<![endif]-->
<style>
ul
{
border:1px solid #ccc;
width:200px;
padding:0;
}
li
{
list-style-type: none;
}
ul li:nth-child(2n+2) {
background-color:#9f9f9f;
width:200px;
padding:0;
}
</style>
</head>
<body>
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
<li>Fifth</li>
</ul>
</body>
</html>
If you want to download IE7-js you can download from here : Click here
9 comments:
Thanks for pointing out... now IE8 it supports.
Post updated!! Thank you guys you are simply awesome.
Please let me know if anything needs to be updated.
Thank You so much! It is really helpful. Now my lists are showing same result as other modern browsers.
Does't work at least with IE8
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.
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.
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?
Your blog has given me that thing which I never expect to get from all over the websites. Nice post guys!
This works on IE-v11 also give a try. Happy coding
Post a Comment