Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style the First Occurence of a Class [duplicate]

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.

like image 265
Paul Grimshaw Avatar asked Jan 19 '14 08:01

Paul Grimshaw


2 Answers

You can try this : (jq solution)

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

enter image description here

like image 21
Royi Namir Avatar answered Sep 27 '22 23:09

Royi Namir


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 +
like image 129
Denys Séguret Avatar answered Sep 27 '22 23:09

Denys Séguret