Use jQuery to Mimic nth-child Behavior in IE8

Nth-child pseudo-selectors are a cool way to supercharge your CSS. They do a great job of styling a group of elements that need slight changes based on their order. A popular example of this is a grid system, or any similar list of items.

This works great in modern browsers, but if you are developing sites that need to be compatible with IE8 and below, you’ll find that :nth-child does not work.

You can use an alternate method to :nth-child by explicitly chaining elements together with the ‘+’ selector. This will select adjacent siblings. However, this method does not scale well and will likely break if your list is dynamic. Below is an example:

 ul > li:first-child + li + li { color: red; } /* find the 3rd list item and color it red */ 


Instead, use conditional comments in your HTML and leverage jQuery to add IE specific selectors in your CSS to recreate nth-child rules.


<!--[if lt IE 9]>
    <link rel="stylesheet" type="text/css" href="css/ie-style.css">
    <script src="scripts/vendor/jquery.min.js"></script>
    <script src="scripts/nth-child-fixer.js"></script>

Continue reading