Why does this not work? http://jsfiddle.net/84C5W/1/
p{
display: none;
}
p.visible:last-of-type {
display: block;
}
<div>
<p class="visible">This should be hidden</p>
<p class="visible">This should be displayed</p>
<p class="">This should be hidden</p>
</div>
In fact, none of my <p> elements are visible. If I remove the reference to .visible in my selector, this does show the last <p> in the div, but this is not what I want.
Of course I could only keep one .visible at all times, but this is for a reveal.js presentation and I do not have control over the JavaScript.
How can I select the last element inside the div WITH the class .visible? I do NOT want to use JavaScript for this.
Your issue is that you’re reading
:last-of-typeand thinking it works as a:last-of-classselector, when instead it specifically means elements only. There is no selector for the last instance of a class, unfortunately.From the W3C:
You have
p.visible:last-of-typeas your selector, which does the following::last-of-typeapplied to it) within each containing element in your HTML<p>element.visibleon it.In short, your selector will only apply its styles to a
<p>that also has the class.visibleon it. In your markup, only the first two<p>elements have that class; the third does not.Here’s a demo of different styles to illustrate:
Per your ultimate goal,
The simplest and most performant way is to invert the way you’re trying to apply the styles; instead of trying to hide two out of three divs, where one of the divs to hide has a class and the other div to hide has no class, and the div you want to show shares the same class as the one div you want to hide which also has a class (see? that’s pretty confusing), do the following:
As you can see from this demo, not only are your HTML and CSS simpler, but this also has the benefit of using only a class selector rather than a
*-of-typepseudo-selector, which will make the page load faster (see more on that below).Why is there no followed by or parent selector?
This could potentially bog down the speed of a lot of webpages by changing just one class name dynamically on the page.
Dave Hyatt, while working on the WebKit implementation in 2008, mentioned some reasons why these implementations are avoided: