Problem: How to Make Internet Explorer 8 (Partially) Support nth-child() CSS

Let's say for example, I have a product list, where I have three products per row. I want to make the spacing equal by using something like:

ul.product-grid li.product:nth-child(3n+2) {;
  margin: 0 7.6% 60px;

Wow, that's a mouthful. And by the way, the first product on each row has an extra class of first. This same selector can be created in many ways, but lets say this is how the client has it already live/on Production and you're not allowed to edit their live CSS, but can addon to it.

Solution 1: Polyfill

One simple answer. Selectivzr, the JavaScript utility. This works for IE6-8. Or you can try some of the stuff below.

Solution 2: JQuery

Ah, you like the back handed way of doing things, eh? Hehe anwyays, you can use JQuery's nth-child selector. This is pretty much like using CSS in your JavaScript file. If I want to make the second list item in my product list have these margins, I can just force the CSS on the item.

$( "ul.product-grid li.product:nth-child(3n+2)" ).css( "margin" , "0 7.6% 60px" );

Look at you! Maybe you can even add a body class of .ie through JavaScript or use conditional comments so that this only applies to Internet Explorer.

$( " ul.product-grid li.product:nth-child(3n+2)" ).css( "margin" , "0 7.6% 60px" );

Solution 3: Adjacent Selectors

One way I do like, and mind you, this way works only on simple selectors, is using the plus sign to target adjacent selectors. You can use psuedo selectors like first-child along with it.

For IE8, we can target the second li element that has the margins, by simply using the first li in the unordered list, and adding an adjacent selector. I'm repeating myself so that this word burns into your brain. ul.product-grid li.product.first + li {
  margin: 0 7.6% 60px;

See what was done here? It looks oddly simple, compared to that crazy :nth-child() mess above. And the point is, it works. I was able to have the client's list items separate properly from the middle list item, by looking for the list item with the class of first (which was located on every row) and getting the list item immediately following it. Why didn't they just do that in the first place, you say?

Who knows. Adjacent selectors do not work in IE6 (who cares?). You can use adjacent selectors to select items that follow each other in DOM order, but they have to share the same parent. Other words for adjacent selector is adjacent-sibling selector or next-sibling selectors or just siblings.

Hope this works out for you! Remember, this only works for simple selectors, nothing too complex like picking every other element or something. You can get crazy with it!

ul > li {}
ul > li + li {}
ul > li + li + li {}
ul li:first-child + li {}
ul li.first + li

I hope this helps!

Add comment

Security code


Visit Betfair Review