Some stuff
Some stuff

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
source share
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; } 

Template Documentation +:

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

Demonstration

Documentation :not

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
source

You can try the following: (jq solution)

$(".meat:eq(0),.dairy:eq(0)").css('color','red');

enter image description here

+2
source

All Articles