为什么".post p:first-child"没有从我的HTML代码(文章)中选择我想要的内容?



My HTML Code:

<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>因为这是类.post的第一个元素子<p>

你能解释一下吗?

提前谢谢。

由于您没有直接后代选择器 (>(,它将选择.post任何后代的任何第一个子代。

要获得所需的结果,您必须编写 .post > p:first-of-type ,这将选择要出现在 .post 中的第一个直接子元素p

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

最新更新