CSS to match the last match of a selector?

2019-04-19 06:28发布

问题:

I have a structure like:

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

I need the last .box element to have an orange background.

.box:last-child{} won't work because it isn't the last child. Apart from wrapping only the .box's in an element, is there any way to do this? This problem does represent what I'm trying to do, but I'd also like to know if there is a way to match the last matched element of a selector.

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

Extra notes:

  • No javascript
  • No giving the last element an extra class

回答1:

Sorry, aside from abusing sibling combinators or :nth-last-child() in a way that depends fully on your HTML structure1, it's currently not possible with CSS selectors alone.

This very feature looks slated to be added to Selectors 4 as :nth-last-match(), though, which in your case would be used like this:

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

But I don't know if the syntax is going to change or when vendors will start implementing it, so let's just leave that as a hypothetical-theoretical-maybe kind of thing for now.


1 Something like this, given that your last .box is also the second last child:

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


回答2:

You can give nth-last-of-type() for a workaround

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

Demo

However, here is also another way of getting this done

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

Then, you can use

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

Demo



回答3:

You could use this css selector if you know that your box class that you want with the orange background is always the second last.

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


回答4:

div:nth-last-child(2){
    background-color: orange; 
}