I have some HTML that looks like this:
<div class="SomeContainer">
<div class="MyClass"></div>
<div class="MyClass"></div>
<div class="MyClass"></div>
<div class="MyOtherClass"></div>
</div>
And I use the following CSS
.MyClass{...}
.MyClass:last-child{box-shadow:0px 5px 10px black;}
I wrongly assumed that last-child operated on the last child of a certain class but it actually operates on the last-child of the container if it’s of the same class.
Is there some convenient way around? I know I could add a wrapper around the MyClass div and add the CSS for the shadow to the wrapper but I was wondering if there’s a better way to do it.
Thanks.
Since you’ve already tried using CSS3 selectors then
this is the correct pseudo class to useAccording to CSS3 specification (at least as I understand it) this should work but it seems it doesn’t. At least not in latest Chrome (v23) and Firefox (v17) browser versions.
Additional investigation
Here’s a JSFiddle that shows how this pseudo class selector actually works:
This means (as my example also shows) that several sibling elements can satisfy this selector as long as they’re of different type.
This seems to work the same way in Chrome and Firefox. And if we carefully read specification it does say
If it said that it’s the last sibling that satisfied selector then my upper solution would work. So lets test my steps.
Run steps through using your HTML
divOther couple of examples in my fiddle
Just to test this pseudo class selector behaviour I added two additional examples. Here’s the HTML:
In the first one two elements satisfy selector (last
divand lastp).In the second one one element satisfies selector (last
div)Outcome
Having HTML that you provided and assuming that there can be an arbitrary number of elements with
.MyClassthere’s no way to write a general selector in CSS3 that would actually target the last element with particular CSS class.The best way is to add additional class to elements that represent the last one with particular class and write a selector to target that.