tusharmath
tusharmath

Reputation: 11002

CSS selector to select the first element after n elements

Is there a way to select the first element with a some class after n elements? For example in the following HTML, I want to be able to select only the first div that has CSS class apple after the 5th div, resulting in the 7th div element being selected.

<div>
    <div class="data-class">1</div>
    <div class="data-class">2</div>
    <div class="data-class">3</div>
    <div class="data-class apple">4</div>
    <div class="data-class">5</div>
    <div class="data-class">6</div>
    <div class="data-class apple">7</div>
    <div class="data-class apple">8</div>
    <div class="data-class">9</div>
    <div class="data-class apple">10</div>
</div>

This selector selects all the divs, but I only want the first: .data-class.apple:nth-child(n+5)

And this one doesn't even work: .data-class.apple:nth-child(n+5):first-child

I have put the HTML and CSS samples here.

UPDATE
Current CSS selectors

.data-class{
  background-color: #0ea;
  padding: 10px;
  margin-bottom: 5px;
  border: 1px solid #444;
}

.data-class:nth-child(n+5)+.apple{
  background-color: #f0f;
}

Upvotes: 2

Views: 1811

Answers (3)

Kisspa
Kisspa

Reputation: 584

It uses this test:

div > .data-class.apple, .data-class{.....}

or another use:

div > .apple:not(.data-class){.....}

Upvotes: 0

BoltClock
BoltClock

Reputation: 724502

To select an element appearing after some other element, use the ~ combinator:

.data-class:nth-child(5) ~ .data-class.apple {
  background-color: #f0f;
}

You won't be able to match only the first .apple that occurs using just one selector. You will need to create another rule to undo the styles that you apply for subsequent .apple elements:

.data-class:nth-child(5) ~ .data-class.apple ~ .data-class.apple {
  background-color: #0ea;
}

This technique is explained here.

Upvotes: 3

changtung
changtung

Reputation: 1624

it is better to say having css class, not having css. I couldn't find the appropiate selector strictly. Instead of this, you could use jquery and write javascript function which use for loop from 5th child until it finds class containing apple. You may use jquery n-th-child to select child in loop and hasClass to determine if it contains apple. Therefore select result by passing result to n-th-child function.

Upvotes: 0

Related Questions