【问题标题】:CSS to match the last match of a selector?CSS以匹配选择器的最后一个匹配项?
【发布时间】:2012-09-06 22:05:37
【问题描述】:

我有这样的结构:

<div id="holder">
    <div id="first"></div>
    <div class="box">I'm the first</div>
    <div class="box">Nothing special</div>
    <div class="box">Nothing special</div>
    <div class="box">Nothing special</div>
    <div class="box">Nothing special</div>
    <div class="box">Nothing special</div>
    <div class="box">Make this background orange!!!</div>
    <div id="last"></div>
</div>​

我需要最后一个 .box 元素具有橙色背景。

.box:last-child{} 不起作用,因为它不是最后一个孩子。除了仅将.box 包装在一个元素中之外,还有什么方法可以做到这一点?这个问题确实代表了我正在尝试做的事情,但我也想知道是否有办法匹配选择器的最后一个匹配元素。

http://jsfiddle.net/walkerneo/KUa8B/1/

补充说明:

  • 没有 JavaScript
  • 不给最后一个元素一个额外的类

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    抱歉,除了以完全依赖于您的 HTML 结构的方式滥用同级组合器或 :nth-last-child()1,目前仅使用 CSS 选择器是不可能的。

    这个功能看起来将作为 :nth-last-match() 添加到 Selectors 4 中,但在您的情况下,它会像这样使用:

    :nth-last-match(1 of .box) {
        background: orange;
    }
    

    但我不知道语法是否会改变或供应商何时开始实施它,所以让我们暂时把它作为一种假设的-理论上的-可能的事情。


    1类似这样,因为你的最后一个 .box 也是倒数第二个孩子:

    .box:nth-last-child(2) {
        background: orange;
    }
    

    【讨论】:

    • 即便如此,它也不能再使用十年(由 IE 提供)。嗯,现在我知道了。谢谢!
    • @Walkerneo:我相信微软会在 IE12 中尝试一下。
    • CSS 和 ECMAscript 版本是否参考规范?
    • 我的意思是 CSS 和 javacript 是基于浏览器实现的,对吧?如果是这样,那么你也不能真正更新,你只能更新浏览器的规范来更新吧?
    • 根据 W3C 的理想,他们发布了一个供浏览器实现的规范,这有点目前正在发生的事情,是的。但是现在我们有供应商前缀和浏览器竞争使事情变得复杂(如果我正确地阅读了你的评论)......
    【解决方案2】:

    你可以给nth-last-of-type()一个解决方法

    #holder > .box:nth-last-of-type(2) {
        background:orange;
    }
    

    Demo

    但是,这也是完成此操作的另一种方法

    <div id="holder">
        <div id="first"></div>
        <div class="boxes">
            <div class="box">I'm the first</div>
            <div class="box">Nothing special</div>
            <div class="box">Nothing special</div>
            <div class="box">Nothing special</div>
            <div class="box">Nothing special</div>
            <div class="box">Nothing special</div>
            <div class="box">Make this background orange!!!</div>
        </div>
        <div id="last"></div>
    </div>
    

    然后,你可以使用

    .boxes .box:last-child {
        background:orange;
    }
    

    Demo

    【讨论】:

    • :last-child:nth-last-of-type(2) 的跨浏览器如何兼容?如果需要#first#last 元素怎么办?
    • @BoltClock,我错了,我以为 IE 7 采用了last-child
    • @BoltClock,而且#first 和#last 还在
    • 我现在看到了,您的回答中缺少它。
    • @BoltClock,我只是把它保存在演示中:)
    【解决方案3】:

    如果你知道你想要的带有橙色背景的盒子类总是倒数第二个,你可以使用这个 css 选择器。

    .box:nth-last-of-type(2){
     background:orange;   
    }
    

    【讨论】:

      【解决方案4】:
      div:nth-last-child(2){
          background-color: orange; 
      }
      

      【讨论】:

        猜你喜欢
        • 2013-09-02
        • 2021-04-11
        • 1970-01-01
        • 2019-11-21
        • 1970-01-01
        • 2015-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多