dbj44
dbj44

Reputation: 1998

Selecting the second occurrence of a class with CSS?

Given the following (dynamic) markup, I need to match the second occurrence of the class orange, regardless of how many divs have the class apple.

<div>
  <div class="apple"></div>
  <div class="apple"></div>
  <div class="orange"></div>
  <div class="apple"></div>
  <div class="apple"></div>
  <div class="orange"></div> <--
  <div class="apple"></div>
</div>

Can it be done with CSS? Thanks.

Upvotes: 3

Views: 7508

Answers (2)

Sergei
Sergei

Reputation: 37

Select second instance of class in HTML like:

<div>
<ul>
<li class="classname">text</li>
<li>text</li>
...
<li>text</li>
<li class="classname">text</li>
<li>text</li>
</div>

Using this CSS (tested in Chrome).

div ul li.classname ~ .classname:not(.classname ~ .classname ~ .classname)

In this particular case :nth-child(2) or :nth-of-type(2) not works.

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

You can use this with selectors level 3 to select those that aren't the first one :

.orange ~ .orange {
}

Demonstration

The best is to complete the style with a rule describing the other .orange elements :

.orange, .orange ~ .orange ~ .orange {
}

Demonstration

Upvotes: 9

Related Questions