Problem
How do you apply a style to only the first element with a certain class?
.just-this-one { background:blue; }
<div class="top"> <div class="not-this-one">not this one</div> <div class="just-this-one">just this one</div> <div class="just-this-one">but not really</div> </div>
:first-child does not do this, that just selects the very first child no matter what the class is.
:first-of-type doesn’t even do this. but you would think it does, but “type” here implies the HTML element type like “div”, “p”, etc.
Solution
Use the tilde “~” to “undo” styles on elements where the class previously appeared. So first apply the style you want to all .just-this-one elements. Then apply “undo” that style for all subsequent elements.
.just-this-one { background:blue; } .just-this-one ~ .just-this-one { background:none; }
This genius solution found on stack overflow (not the accepted answer):
http://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class
Additional note: If you have a pseudo selector like :before, use something like the code below to write content before all li elements except the first one.
.menu li:before { content: ''; } .menu li ~ li:before { content: "\002F\0020\002F"; color: #aaaaaa; }