伪类 :nth-child和:nth-of-type的顺序问题

html代码:

<body>
    <header>
        <h1>知识</h1>
        <!-- 设置下边阴影 -->
    </header>
    <main>
        <section>
            <div>
                <p>1</p>
                <p>2</p>
                <p>3</p>
            </div>
            <p>1</p>
            <p>2</p>
            <p>3</p>
            <p>4</p>
            <div>
                <p>1</p>
                <p>2</p>
                <p>3</p>
                <p>4</p>
            </div>
            <p>1</p>
            <p>2</p>
            <p>3</p>
            <p>4</p>
        </section>
        <aside>
            <!-- 侧栏目录 -->
        </aside>
    </main>
    <footer>
    </footer>
</body>

</html>

css代码:

/* div :nth-of-type(odd) {
    background-color: green;
} */

section :nth-child(odd) {
    background-color: green;
}

p:nth-child(odd) {
    color: red;
}

问题就在与排序的问题,
顺序分为了两段进行渲染,我搞不懂。。。选择的原理,只知道nth-child如果确定第几个子元素,但不是该tag就会渲染失效,但是这里显然不是这个问题。

阅读 1.2k
1 个回答
section :nth-child(odd) {
background-color: green;
}

这段就是 <section> 里面每个元素第odd个背景是绿色(包括section元素),相当于加了*(通配符)

p:nth-child(odd) {
color: red;
}

这段就是p下第odd个元素,把上面的*变成p

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题