<分区>
<分区>
我的 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>
因为这是第一个元素 child <p>
类(class) .post
你能解释一下吗?
提前致谢。
最佳答案
由于您没有直接后代选择器 (>
),它将选择 .post
的任何后代的任何第一个 child 。
要得到你想要的结果,你必须写.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/