如何使用CSS2选择器获取元素的第n个孩子? [英] How do I get the nth child of an element using CSS2 selectors?

查看:785
本文介绍了如何使用CSS2选择器获取元素的第n个孩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有可能获得CSS2中有序列表的第n个元素吗?

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

(类似于:nth-​​child / code> in CSS3)

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

FYI:我试图将德语版Parcheesi XHTML 1.1和CSS2兼容,并试图通过使用有序列表生成游戏区,所以移动选项由数据结构预先确定。

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.

推荐答案

您可以使用相邻的同级组合器 :first-child 伪类,根据需要重复组合器多次一个特定的第n个孩子。 另一个问题的答案也提及了这一点。

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.

对于任何元素 E ,从 E:first-child 开始,然后添加 + E 为后续的子元素,直到到达您定位的元素。当然,你不必使用相同的元素 E ;你可以切换任何类型,类,ID等等,但重要的位是:first-child + 标志。

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.

例如,要获取的第三个 li ol ,以下CSS3选择器:

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

ol > li:nth-child(3)

将在CSS2中复制:

ol > li:first-child + li + li

例如:

<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>

请注意,由于没有查看先于同级的同级组合器(无论在CSS2还是CSS3中),都不能模拟:nth-​​last -child():last-child 使用CSS2选择器。

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.

你每次只能为一个特定的孩子模拟:nth-​​child(b),其中 b 公式中的数字 an + b (如中所述) spec );您不能单独使用相邻的兄弟组合器来实现任何复杂的公式。

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.

这篇关于如何使用CSS2选择器获取元素的第n个孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆