【问题标题】:How do I get the nth child of an element using CSS2 selectors?如何使用 CSS2 选择器获取元素的第 n 个子元素?
【发布时间】:2012-03-29 18:21:05
【问题描述】:

有没有可能在 CSS2 中获取有序列表的第 n 个元素?

(类似于 CSS3 中的:nth-child()


仅供参考:我正在尝试将德国版 Parcheesi 编程为兼容 XHTML 1.1 和 CSS2,并尝试使用有序列表生成运动场,因此移动选项由数据结构预先确定。为了定位围绕中心的方式,我想按数字选择列表元素。

【问题讨论】:

    标签: css css-selectors


    【解决方案1】:

    您可以将adjacent sibling combinators:first-child pseudo-class 结合使用,根据需要多次重复组合子以达到某个特定的第n 个孩子。 an answer to a different question中也提到了这一点。

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

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

    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>
    

    请注意,由于 there are no sibling combinators that look at preceding siblings(既不在 CSS2 也不在 CSS3 中),您无法使用 CSS2 选择器模拟 :nth-last-child():last-child

    此外,您一次只能为一个特定的孩子模拟:nth-child(b),其中b 是公式an+b 中的一个常数(如spec 中所述);您无法仅使用相邻的兄弟组合子来实现任何复杂的公式。

    【讨论】:

      【解决方案2】:

      不,你不能。 nth-child() 是在 CSS3 中引入的,所以我认为没有办法解决这个问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-04-24
        • 2021-10-03
        • 1970-01-01
        • 2013-04-26
        • 1970-01-01
        • 1970-01-01
        • 2018-08-07
        相关资源
        最近更新 更多