Class first appearance style
I have a stack of divs:
<div> <div class="meat">Some stuff</div> <div class="meat">Some stuff</div> <div class="meat">Some stuff</div> <div class="meat">Some stuff</div> <div class="dairy">Some stuff</div> <div class="dairy">Some stuff</div> <div class="dairy">Some stuff</div> </div> I need to style the first of each class and not have html control ... preferably pure CSS, but jQuery will also work.
+6
2 answers
Solution 1: Define a specific style for elements that are not first:
.meat { // applies to all } .meat + .meat { // applies to those that aren't the first one } For example, if you want to red the first .meat element, do the following:
.meat { color: red; } .meat+.meat{ color: inherit; } E + F Matches any element F immediately preceded by sibling E.
Solution 2: Use :not in combination with + and first-child :
.dairy:first-child, :not(.dairy)+.dairy { color: red; } This selector is for any element in the dairy class that is either
- the first child (and therefore the first of his classes in the parent) or
- after another element whose class is not
dairy
Notes:
- these selectors are not available in IE8 (but not many modern networks, Google even stopped supporting IE9 in GMail ...).
- If you want to apply the same rule, but with possible intermediate elements, you should use
~instead of+
+8
