Html CSS是否匹配选择器的最后一个匹配项?

Html CSS是否匹配选择器的最后一个匹配项?,html,css,css-selectors,Html,Css,Css Selectors,我的结构如下: <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 clas

我的结构如下:

<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:最后一个子项{}
将不起作用,因为它不是最后一个子项。除了在元素中只包装
.box
,还有什么方法可以做到这一点吗?这个问题确实代表了我试图做的事情,但我也想知道是否有方法匹配选择器的最后一个匹配元素

附加说明:

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

对不起,除了滥用兄弟组合符或
:nth-last-child()
完全取决于您的HTML结构之外,目前仅使用CSS选择器是不可能的

这项功能看起来将被添加到选择器4中,但在您的情况下,它的使用方式如下:

:nth-last-match(1 of .box) {
    background: orange;
}
但我不知道语法是否会改变,也不知道供应商何时会开始实现它,所以让我们暂时把它作为一个假设的理论问题


1类似的情况,考虑到您的最后一个
.box
也是最后一个孩子:


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

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

您可以给出
nth-last-of-type()
作为解决方法

#holder > .box:nth-last-of-type(2) {
    background:orange;
}
然而,这里还有另一种方法来实现这一点

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

即使这样,它也不能再使用十年(由IE提供)。现在我知道了。谢谢@沃克诺:我相信微软会在IE12中尝试一下。CSS和ECMAscript版本是否参考了规范?我的意思是CSS和JavaScript是基于浏览器实现的,对吗?如果是这样的话,那么你也不能真正更新,你只能更新浏览器的规范来更新,对吗?根据W3C的理念,他们发布了一个浏览器的规范来实现,这是目前发生的事情,是的。但是现在我们有供应商前缀和浏览器竞争,这让事情变得复杂了(如果我没看错你的评论的话).
:last child
:nth last of type(2)
的跨浏览器兼容性如何?如果
#first
#last
元素是必需的,怎么办?@BoltClock,我错了,我以为IE 7接受了
last child
@BoltClock,而且#first和#last仍然在那里我现在看到了,你的答案中缺少了它。@BoltClock,我刚刚把它保存在演示中:)
#holder > .box:nth-last-of-type(2) {
    background:orange;
}
<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;
}