I have the following markup:
<div class="a"></div>
<div class="b"></div> <!-- :first -->
<div class="b"></div>
<div class="b"></div> <!-- :last -->
<div class="c"></div>
I’m trying to target the first and last <div> with class b.
If I was using jQuery selectors for this, .b:first and .b:last would do the trick.
However with CSS, that’s tricky: the first <div class="b"> is located after another <div> with a different class, and both :first-child and :first-of-type match the first <div>, with class a.
Is there a selector targeting the first of the items matching the class?
No, there is no equivalent CSS selector to jQuery’s
:firstor:lastselector, because those selectors are filters, and not true simple selectors by the CSS definition.In Selectors 3 there is no
:first-of-classor similar selector either.However, you can use overriding rules with the
~combinator to apply styles to the first child of a certain class:But there is currently no way to apply styles to the last child of a certain class using CSS: