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

标签 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>因为这是第一个元素 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/

上一篇:html - 为什么这个 img 属性不起作用?

下一篇:javascript - 如何从另一组更大的按钮中单独更改一组按钮的颜色

相关文章:

javascript - 使用 Javascript 在 div 元素之间切换

html - 边距/填充位于 div 之外

html - Bootstrap 网格列大小不适用于实现样式化的下拉列表

html - 使用 CSS 去除空白

php - 显示内联 block ,它在 HTML 中工作但在 PHP 中不工作(我在数据库中获取值)

javascript - 如何在函数调用时访问数组中的对象

html - 如何使用css使标题变粘

html - 即使帐户已获得授权,也会出现 HTTP 错误 500

html - 在 Bootstrap 中设置缩进的 h4 元素的样式

html - 用响应式 <image> 填充一个 div 并居中放置