3

I have elements of a given secondclass with grey background and I would like only even elements of this class with a red background. I can't use nth-child() selector because these elements might not be the only inside parent.

I've tried the following:

.secondclass {
    background-color:#aaa;
}

.secondclass:nth-of-type(2n+1) {
    background-color:red;
}

This works fine until I put an element of the same type of secondclass inside parent (i.e. a div). This is reasonable, since nth-of-type() refers to the type not the class:

<div>some text</div>
<div class="secondclass"></div>
<div class="secondclass"></div>

Fiddle

Is there a pure-CSS way to select only even elements of secondclass subset, independently from their type?

Giorgio
  • 1,940
  • 5
  • 39
  • 64
  • possible duplicate of [css3 nth of type restricted to class](http://stackoverflow.com/questions/10921809/css3-nth-of-type-restricted-to-class) – Jakub Kotrs Oct 16 '14 at 14:41

2 Answers2

2

Why not just make 2 classes for the even and uneven and just assign these classes where it is necessary? Otherwise trying to figure out how to make a logic check within CSS seems a very long detour to the same result.

The class for "even" elements will have red background and "uneven" will have grey background.

.uneven {
    background-color:#aaa;
}

.even {
    background-color:red;
}

And the divs:

<div>some text</div>
<div class="uneven"></div>
<div class="even"></div>
Code Whisperer
  • 1,041
  • 8
  • 16
1

Only one way which I see is use different HTML tag. Like:

<div>some text</div>
<span class="secondclass"></span>
<span class="secondclass"></span>

Demo:

JS fiddle

But there is no pure CSS solution

LJ Wadowski
  • 6,424
  • 11
  • 43
  • 76