:Nth-Child(Even/Odd) Selector with Class

:nth-child(even/odd) selector with class

In general what you want is not possible, but there is a way to achieve the desired behavior for limited numbers of "excluded" elements: the general sibling combinator ~.

The idea is that for each occurrence of a non-.parent element subsequent .parent elements will have their colors toggled:

.parent:nth-child(odd) {
background-color: green;
}
.parent:nth-child(even) {
background-color: red;
}

/* after the first non-.parent, toggle colors */
li:not(.parent) ~ .parent:nth-child(odd) {
background-color: red;
}
li:not(.parent) ~ .parent:nth-child(even) {
background-color: green;
}

/* after the second non-.parent, toggle again */
li:not(.parent) ~ li:not(.parent) ~ .parent:nth-child(odd) {
background-color: green;
}
li:not(.parent) ~ li:not(.parent) ~ .parent:nth-child(even) {
background-color: red;
}

See it in action.

Of course there is a limit to how far one would be willing to take this, but it's as close as you can get with pure CSS.

nth child even/odd selector

Change the last rule to:

#commercialNav li:nth-child(odd) a{
color:#215034;
}

jsFiddle example

The anchors aren't children of the #commercialNav div (although they are descendants), so that particular selector you were trying won't work. If you didn't have the list items in there then the rule would work, but since the anchors aren't sibling of each other, you need to use the selectors as I show above.

Select odd even child excluding the hidden child

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.

Why .class_name:nth-child(even) counts elements without .class_name

You are using the :nth-child() selector, whereas you should be using the :nth-of-type() selector: