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

时间:2018-01-15 21:32:43

标签: html css

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

你能解释一下吗?

提前致谢。

1 个答案:

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