nth-child中奇数/偶数子元素的问题

Mar*_*ski 13 html css css-selectors

我有一个这样的网站:

<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>
Run Code Online (Sandbox Code Playgroud)

这是CSS:

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

这就是结果:

结果

这是可以的,因为即使在每个部分,我为奇数div和绿色获得红色.但是当我在第一部分的开头添加标题(示例中的注释代码)时,我得到了这个:

RESULT2

我不希望这样.我希望之前有这样的,但只是在第一部分中有一个标题.所以在第一个标题然后红色段落.

thi*_*dot 51

nth-of-type改为使用:

现场演示

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