6

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 don't have control over the html... preferably pure CSS, but jQuery would also do.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
Paul Grimshaw
  • 19,894
  • 6
  • 40
  • 59

2 Answers2

8

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

Demonstration

Documentation of :not

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 +
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

You can try this : (jq solution)

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

enter image description here

Royi Namir
  • 144,742
  • 138
  • 468
  • 792