This question already has an answer here:
:first-child selector not working
                                
                                    (1个答案)
                                
                        
                                2年前关闭。
            
                    
我的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

你能解释一下吗?

提前致谢。

最佳答案

由于您没有直接后代选择器(>),因此它将选择.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>

关于html - 为什么“.post p:first-child”没有从HTML代码(文章)中选择我想要的内容? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48270954/

10-12 00:17
查看更多