CSS first-child 选择器不选择第一个元素

标签 css css-selectors

为什么如果我在“p”行之前放置一个元素,我看不到第一行是黄色的? p:first-child 应该选择第一个 p 而不仅仅是第一个标签吗?

<style type="text/css">
    p:first-child 
    {
        background:yellow;
    }
</style>


<i></i>
<p>I am a strong man. I am a strong man.</p>
<p>I am a strong man. I am a strong man.</p>
<p>I am a strong man. I am a strong man.</p>

最佳答案

:first-child不关心类型。通过添加 <i></i>到你的代码,i成为第一个 child (当然,假设 <style><head> 内,其余的在 <body> 内)。您的选择器想要匹配 p , 但自 p不再是第一个 child ,您的样式无法应用。

如果要按类型过滤,请使用 CSS3 :first-of-type伪类:

p:first-of-type
{
    background:yellow;
}

关于CSS first-child 选择器不选择第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5548813/

相关文章:

java - :selected pseudoclass style not applied to cell

python - 如何通过 Selenium 和 Python 点击​​表中的 onclick 事件

html - 如何将类更改为超链接 href

css - Nth-child css target 最后一个和第一个 3 个 child

javascript - Android 浏览器中的页脚按钮

css - 为什么我不能覆盖通过星号应用的显示属性?

css - 在less中将伪类添加到父祖先(选择器)

javascript - 突出显示站点内特定样式( float )的所有元素

html - 位置 :relative and left/top 的危险

javascript - 非常简单的javascript来删除文本框中的值