March 27, 2012

CSS to match the last match of a selector?

Question by Walkerneo

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

Answer by BoltClock

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

Answer by Starx

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!