我的HTML代码:
<article class="post" id="first">
<header>
<h1>Title</h1>
</header>
<p>First paragraph</p>
<p>Second paragraph</p>
<footer>
<p>This is a footer</p>
</footer>
</article>
我的CSS代码:
.post p:first-child {color: green;}
我无法理解为什么这个段落保持绿色:<p>This is a footer</p>
而不是这一段:<p>First paragraph</p>
因为这是类<p>
的第一个元素.post
< / p>
你能解释一下吗?
提前致谢。
答案 0 :(得分:4)
由于你没有直接的后代选择器(>
),它将选择.post
的任何后代的任何第一个孩子。
要获得所需的结果,您必须写.post > p:first-of-type
,这将选择p
中显示的第一个直接子元素.post
。
.post > p:first-of-type { background-color: green; }
<article class="post" id="first">
<header>
<h1>Title</h1>
</header>
<p>First paragraph</p>
<p>Second paragraph</p>
<footer>
<p>This is a footer</p>
</footer>
</article>