Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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

Problem

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.

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?

Problem courtesy of: Jeremy Holovacs

Solution

: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.

Solution courtesy of: Kaivosukeltaja

Discussion

View additional discussion.



This post first appeared on CSS3 Recipes - The Solution To All Your Style Problems, please read the originial post: here

Share the post

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

×

Subscribe to Css3 Recipes - The Solution To All Your Style Problems

Get updates delivered right to your inbox!

Thank you for your subscription

×