caramba caramba - 3 months ago 25
CSS Question

Select odd even child excluding the hidden child

Between line 2 and 3 is a hidden

<div>
. I don't want that one to be taken from the
odd/even css
rule.
What would be the best approach to get this to work? http://jsfiddle.net/k0wzoweh/

enter image description here

<style>
.box:not(.hidden):nth-child(even) {background: green}
.box:not(.hidden):nth-child(odd) {background: orange}
.hidden {display:none;}
</style>
<div class="wrap">
<div class="box">xx</div>
<div class="box">xx</div>
<div class="box hidden">xx</div>
<div class="box">xx</div>
<div class="box">xx</div>
<div class="box">xx</div>
<div class="box">xx</div>
</div>

Joe Joe
Answer

Pseudo-selectors don't stack, so your :not doesn't affect the :nth-child (nor would it affect :nth-of-type etc.

If you can resort to jQuery, you can use the :visible pseudo-selector there, although that's not a part of the CSS spec.

If you're generating the HTML and can change that, you can apply odd/even with logic at run-time, eg in PHP:

foreach ($divs AS $i => $div) {
    echo '<div class="box ' . ($i % 2 ? 'even' : 'odd') . '">x</div>';
}

Even trying to do something tricky like

.box[class='box']:nth-of-type(even)

doesn't work, because the psuedo-selector doesn't even stack onto the attribute selector.

I'm not sure there's any way to do this purely with CSS - I can't think of any right now.

Comments