I have a stack of divs:
Some stuff
Some stuff
Some stuff
Some stuff
Some stuff
Some stuff
Some stuff
I need to style the first of each class, and don't have control over the html... preferably pure CSS, but jQuery would also do.
Answer
Solution 1 : Define a specific style for elements that are not the first one :
.meat {
// applies to all
}
.meat + .meat {
// applies to those that aren't the first one
}
For example, if you want to color in red the first .meat
element, do this :
.meat {
color: red;
}
.meat+.meat{
color: inherit;
}
Documentation about the + pattern :
E + F Matches any F element immediately preceded by a sibling element E.
Solution 2 : Use :not
in combination with +
and first-child
:
.dairy:first-child, :not(.dairy)+.dairy {
color: red;
}
This selector targets any element of class dairy
which is either
- the first child (and thus the first of its class in the parent) or
- following another element whose class isn't
dairy
Notes :
- those selectors aren't available on IE8 (but not a lot of the modern web is, Google even stopped support of IE9 in GMail...).
- if you wanted to apply the same kind of rule but with possible intermediate elements, you'd use
~
instead of+
No comments:
Post a Comment