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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5195367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:06:14  来源:igfitidea点击:

Problem with odd/even child elements in nth-child

csshtmlcss-selectors

提问by Mariusz Pawelski

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:

这是 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:

这是结果:

result

结果

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

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

result2

结果2

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.

我不想要那个。我想要像以前一样,但只是在第一部分有一个标题。所以首先是标题,然后是红色段落。

回答by thirtydot

Use nth-of-typeinstead:

使用nth-of-type来代替:

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;
}

回答by Avinash Saini

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