21

Is there any possibility to get the nth element of an ordered list in CSS2?

(similar to :nth-child() in CSS3)


FYI: I'm trying to program the German version of Parcheesi to be XHTML 1.1 and CSS2 compliant and trying to generate the playfield by using ordered lists, so movement options are predetermined by the data structure. For positioning the way around the center I'd like to select the list elements by number.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
myAces
  • 679
  • 1
  • 5
  • 13

2 Answers2

28

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.

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
2

No you can't. nth-child() got introduced in CSS3 , so I don't think that there is an way around that problem.

mas-designs
  • 7,498
  • 1
  • 31
  • 56