【问题标题】:CSS: styling list items based on the order in which they appear rather than on classes?CSS:基于它们出现的顺序而不是类来样式化列表项?
【发布时间】:2012-07-17 13:50:45
【问题描述】:

我使用的 CMS 生成的站点地图几乎没有样式选项,基本上,它不允许我向列表项添加类,我需要它们为它们提供不同的背景颜色。

现在我知道有 first-child 和 last-child 伪类可以让我为列表中的第一个和最后一个项目设置样式,但是如果有任何 CSS 可以让我调用列表中的其他项目不能给他们分配一个班级?

【问题讨论】:

  • 问题中的“CSS 2”令人困惑——它是“CSS level 2”还是“CSS to”?请注意,:last-child 在 CSS2 中不存在,只有 :first-child 存在。

标签: css css-selectors html-lists


【解决方案1】:

使用来自 CSS3 的 :nth-child()

/* select the third element if it's an li */
li:nth-child(3) {
    background-color: yellow;
}

:nth-child() won't work 在 IE8 等旧浏览器中,但there's a CSS2 workaround

【讨论】:

【解决方案2】:

nth-child, nth-of-type

示例:

选择列表中的第二项

li:nth-child(2) {/*styles*/}

选择奇数列表项

li:nth-child(odd) {/*styles*/}

选择第3,第6,第9,...列表项

li:nth-child(3n) {/*styles*/}

选择第 1 个、第 5 个、第 9 个、...列表项

li:nth-child(4n+1) {/*styles*/}

【讨论】:

    【解决方案3】:

    CSS2 不支持 :nth-child(n),也许你可以为

      制作背景图像,颜色在正确的位置。但我说用旧浏览器搞砸的人;)

    【讨论】:

      【解决方案4】:

      使用 CSS2,也许不会。使用 CSS3,有 nth-child() 选择器:

      element:nth-child(2) { ... }
      

      上面会得到第二个孩子。

      jsFiddle

      否则,您可以使用 JavaScript/jQuery 来获得您想要的结果。这是一个 jQuery 示例:

      $(function () {
          $('selector').eq(1).css('background', 'blue');
      });​
      

      jsFiddle

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-05
        • 2011-11-15
        • 1970-01-01
        • 2018-01-08
        • 2013-12-24
        • 1970-01-01
        • 2013-03-18
        • 2012-03-03
        相关资源
        最近更新 更多