CSS第一子选择器问题

时间:2011-04-05 07:52:29

标签: css css-selectors

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

为什么如果我把一个元素放在“p”行之前,我看不到第一行是黄色的? 应该p:第一个孩子选择第一个“p”而不只是第一个标签?

感谢

1 个答案:

答案 0 :(得分:11)

:first-child并不关心这种类型。通过在代码中添加<i></i>i成为第一个孩子(假设<style><head>内,其余的在<body>中,当然)。您的选择器要匹配p,但由于p不再是第一个孩子,因此无法应用您的风格。

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

p:first-of-type
{
    background:yellow;
}
相关问题