Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS to match the last match of a selector?

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
like image 309
mowwwalker Avatar asked Mar 27 '12 01:03

mowwwalker


1 Answers

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.


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

.box:nth-last-child(2) {
    background: orange;
}
like image 118
BoltClock Avatar answered Oct 04 '22 22:10

BoltClock