如果标题存在,第一个子选择器不工作 [英] First child selector doesn't work if header is present

查看:109
本文介绍了如果标题存在,第一个子选择器不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的HTML标头和一些部分。

I have a simple HTML with an header and some sections.

<header>Header</header>
<section>Section 1</section>
<section>Section 2</section>
<section>Section 3</section>

我想给第一部分加上风格

I would like to style the first section

section:first-child {
    background-color:green;    
}

看起来:first: code>选择器不工作时存在( jsfiddle )。当我删除一切正常!为什么?

It seems that the :first:child selector doesn't work when header is present (jsfiddle). When I remove header everything works again! Why?

推荐答案

这是因为< section>

元素:first-child 表示其父元素的第一个子元素,与元素匹配。在你的情况下,父元素的第一个元素是< header> 元素。

element:first-child represents the first child of its parent, matching the element. And in your case, the first element of the parent is a <header> element.

:first-of-type 伪类。

section:first-of-type {
    background-color:green;    
}

MDN


:first-of-type CSS伪类表示其父元素的子元素列表中
类型的第一个兄弟类。

The :first-of-type CSS pseudo-class represents the first sibling of its type in the list of children of its parent element.

这篇关于如果标题存在,第一个子选择器不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆