Problem with odd/even child elements in nth-child

2019-01-15 07:55发布

问题:

I have a web site like this:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="article_style.css" />
</head>
<body>
    <div class="section">
    <!--<h1>header</h1>-->
        <div>
            paragraph
        </div>
        <div>
            paragraph
        </div>
        <div>
            paragraph
        </div>
    </div>
    <div class="section">
        <div>
            paragraph
        </div>
        <div>
            paragraph
        </div>
        <div>
            paragraph
        </div>
    </div>
</body>
</html>

and this is CSS:

div.section
{
    border: 1px solid black;
}
div.section div:nth-child(even)
{
    color: Green;
}
div.section div:nth-child(odd)
{
    color: Red;
}

And this is the result:

This is OK because I get red for odd div and green for even in each section. But when I add header at the begginig of first section (commented code in sample) I get this:

I don't want that. I want the to have like before, but just with a header in first section. So at first header and then red paragraph.

回答1:

Use nth-of-type instead:

Live Demo

div.section
{
    border: 1px solid black;
}
div.section div:nth-of-type(even)
{
    color: Green;
}
div.section div:nth-of-type(odd)
{
    color: Red;
}


回答2:

div > :nth-child(3)     the third child of a div element
div > :nth-child(even)  every even child of a div element
div > :nth-child(odd)   every odd child of a div element
div > :nth-child(3n)    every third child of a div element