user610217
user610217

Reputation:

Using nth-child(odd) does not seem to behave as I would expect

I have a piece of CSS like so:

.formTable:nth-child(odd)
{
    background-color: #eeb;
}

I also have a form with the following basic structure (obviously not the complete HTML). Of note is the dynTable1 that is loaded with an AJAX call in certain circumstances.

<table class="formTable" id="table1" />
<table class="formTable" id="table2" />
<table class="formTable" id="table3" />
<table class="formTable" id="table4" />
<div id="divDynamic1" class="fadeIn">
    <table class="formTable" id="dynTable1" />
</div>

the thing that doesn't make sense to me is, the nth-child selector will key against table2, table4 and dynTable1 on Firefox and IE9 (I did not try others). I would have expected dynTable1 to not have the style applied to it. Clearly my understanding of how nth-child works is lacking, but while my Google-fu uncovered many examples of how to use nth-child, I had difficulty finding a simple explanation of how it worked in this sort of case. So, I turn to SO.

Why does nth-child behave like this, and how can I make it alternate strictly between table elements of class formTable?

Upvotes: 0

Views: 554

Answers (2)

Kaivosukeltaja
Kaivosukeltaja

Reputation: 15735

:nth-child(odd) is applied to elements that are 1st, 3rd, 5th, etc children of their own parent container, not their children. I'm guessing there are some other elements before the .formTables in their parent container? That's why every second table matches the rule, and #dynTable1 matches because it is the 1st child of #divDynamic1.

EDIT: Now that I understand what you're trying to achieve, I can suggest something like this:

.wrapper > div > .formTable
{
    background-color: #ccc;
}

.wrapper > div:nth-child(odd) > .formTable:nth-child(odd)
{
    background-color: #eeb;
}

.wrapper > div:nth-child(even) > .formTable:nth-child(even)
{
    background-color: #eeb;
}
​

What it does is reset the background color of the tables inside the divs, then specifies new alternation rules for the tables inside them - starting from gray if the div is an even child, and yellow if it is an odd child.

Upvotes: 2

Per Salbark
Per Salbark

Reputation: 3645

You are targeting all .formTable. Even the ones in #divDynamic1. (and odd targets the first, third, fifth e.t.c elements, which is why the first table in #divDynamic1 is targeted)

Try using a wrapper to specify that you only want to target children:

.wrapper > .formTable:nth-child(odd)
{
    background-color: #eeb;
}​

Here is a fiddle for you.

Upvotes: 2

Related Questions