css - 仅当父元素是第一个元素时,如何将样式应用于父元素下的特定元素?

标签 css css-selectors parent-child

我需要将样式应用于 p 标记 只有 如果它是父元素下的第一个元素。我已经尝试搜索 Google 和 Stack Overflow,但我可能没有输入正确的搜索来获得我需要的东西,因为我找不到我需要做什么的示例。

如果我需要在下面的代码中将文本更改为红色,我可以使用什么 CSS?

<div class="main">
  <p>This will be red.</p>
  <p>This will not be red.</p>
  <p>This will not be red.</p>
</div>

<div class="main">
  <h1>Title</h1>
  <p>This will not be red.</p>
</div>

<div class="main">
  <img src="" alt="">
  <p>This will not be red.</p>
</div>

最佳答案

:first-child 选择器将执行此操作。

.main p:first-child {
  color: red;
}
<div class="main">
  <p>This will be red.</p>
  <p>This will not be red.</p>
  <p>This will not be red.</p>
</div>

<div class="main">
  <h1>Title</h1>
  <p>This will not be red.</p>
</div>

<div class="main">
  <img src="" alt="">
  <p>This will not be red.</p>
</div>

关于css - 仅当父元素是第一个元素时,如何将样式应用于父元素下的特定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41902984/

相关文章:

css - 这个 css 选择器有什么用?

javascript - 当我在 chrome mobile 中向下滚动时,绝对定位的 DIV 会改变位置,如何解决这个问题?

mysql - SQL从指定类别及其子项中选择所有产品

wordpress - 在转到父主题之前,如何首先使用 include 检查子主题文件?

css - 过滤数据时过渡不平滑

html - 在 css 中围绕文本制作一个完美的正方形 bg?

css - 在 IE6 CSS 中使用双类?

javascript - 用 jquery 改变 .css 类

javascript - 填充导航栏的方法 - Tables/CSS/JS

python - 父类在子类中使用的 settattr