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.

0

2 Answers 2

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 +
Sign up to request clarification or add additional context in comments.

16 Comments

can you explain :not ?
what does the plus sign does in css ?
@FranciscoCorrales I added the documentation of the plus sign.
Can the downvoter explain what he didn't like ?
@FranciscoCorrales I found a "one instruction" solution :)
|
2

You can try this : (jq solution)

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

enter image description here

16 Comments

downvotes explnation would be great.
"preferably pure CSS". This is a CSS question. I don't get why people want to replace a simple, fast CSS selector(s) with a overweight JS lib.
@bjb568 "but jQuery would also do."
That's not your problem. he is the OP and that's what he asked.
You win I dont want to argue.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.