Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...