为什么如果我在“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/