html - CSS :first-child with class selector picking up wrong elements to style?

标签 html css css-selectors

这是HTML代码,我不明白为什么<a>第二个标签 <p>有棕色:

.entry-content :first-child {
  color: brown
}
<article id="post-5946">
  <section class="entry-content">
    <p>
      <a href="#">HTML5 From Scratch</a>Very proud to announce my latest Pluralsight Course:
    </p>
    <p>
      <a href="#">HTML5 From Scratch</a>Very proud to announce my latest Pluralsight Course:
    </p>
  </section>
</article>

当您查看此页面时,我看到两段,第一段和标签都是棕色的,第二段只有棕色,这不应该是这种情况,即第二段的颜色不应该有任何变化。

输出: enter image description here

最佳答案

.entry-content :first-child选择 .entry-content 的所有后代看看他们是否是 parent 的第一个 child 。

自第二个<a>标签是其父标签的第一个子标签并且它是.entry-content 的后代, 它获得了风格。

你只想检查.entry-content的直系 child ,你可以这样做:

.entry-content > :first-child

假设您希望第一段及其内容为棕色,请执行以下操作:

片段:

.entry-content > :first-child,
.entry-content > :first-child * {
  color: brown
}
<section class="entry-content">
  <p>
    <a href="#">HTML5 From Scratch</a>Very proud to announce my latest Pluralsight Course:
  </p>
  <p>
    <a href="#">HTML5 From Scratch</a>Very proud to announce my latest Pluralsight Course:
  </p>
</section>

关于html - CSS :first-child with class selector picking up wrong elements to style?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42303006/

相关文章:

javascript - 将代码从 canvas 转换为 svg

javascript - "JavaScript sanitization doesn' t save you from innerHTML”是什么意思?

python - 将自定义 CSS 样式添加到模型表单 django

CSS 行高/H1 字体大小

html - 当属性为 'width' 时,属性选择器不适用于表

javascript - 测试浏览器是否支持 CSS 选择器

php - 注意:未定义索引product_name

asp.net - 带有 html5shiv 和 SSL 的 IE7 中的混合内容错误

html - 光标不显示在文本字段上

css - CSS "Quote in a Quote"问题