How do I get the nth child of an element using CSS2 selectors?

You can use adjacent sibling combinators in conjunction with the :first-child pseudo-class, repeating the combinators as many times as you need to reach a certain nth child. This is also mentioned in an answer to a different question.

For any element E, start with E:first-child, then add + E for subsequent children until you reach the element that you’re targeting. You don’t have to use the same element E, of course; you could switch that out for any type, class, ID, etc, but the important bits are the :first-child and + signs.

As an example, to get the third li of its ol, the following CSS3 selector:

ol > li:nth-child(3)

Would be replicated in CSS2 like so:

ol > li:first-child + li + li

An illustration:

<ol>
  <li></li> <!-- ol > li:nth-child(1), ol > li:first-child -->
  <li></li> <!-- ol > li:nth-child(2), ol > li:first-child + li -->
  <li></li> <!-- ol > li:nth-child(3), ol > li:first-child + li + li -->
  <li></li> <!-- ol > li:nth-child(4), ol > li:first-child + li + li + li -->
</ol>

Note that since there are no sibling combinators that look at preceding siblings (neither in CSS2 nor CSS3), you cannot emulate :nth-last-child() or :last-child using CSS2 selectors.

Additionally, you can only emulate :nth-child(b) for one specific child at a time, where b is a constant number in the formula an+b (as described in the spec); you can’t achieve any complex formulas with adjacent sibling combinators alone.

Leave a Comment