避免 CSS 某些相邻元素和 类 之间的样式

Avoid CSS styling between certain adjacent elements and classes

我想在 h3body 之间添加 padding-top: 20px;,但如果 h3 前面有另一个元素(例如 h2),则不会。这可能吗?

当标题前面有 body 文本但标题之间有不需要的填充时,将 padding-top 添加到所有标题可提供所需的填充:

请注意,此文档是使用 knitr 创建的 Rmarkdown,因此我无法完全控制所有 html。最好是纯 CSS-solution。


更新: 对于同样使用 knitr 的 Rmarkdown 的任何人来说,解决方案结果是一个相当复杂的定位:

/* First h2 following h1 */
.level1 > .level2:nth-child(3) > h2 {
    padding-top: 0px;
}
/* First h3 following h2 */
.level2 > .level3:nth-child(3) > h3 {
    padding-top: 0px;
}

查看生成的 HTML,我了解到 h1 之后的第一个 h2 位于 level1 中的第三个元素中,并且该元素称为 level2。第一个 h3 也是如此。这就是上面的目标。其他文档中的结构可能不同,请自行查看。

怎么样

body > h3:first-child {
   padding-top: 20px;
}

这只会影响带有 header3 的 body 的直接子节点,中间没有任何内容。

感谢@Oram 指出缺失的 :first-child

试试这个:

body > h3:first-child {
   padding-top: 20px;
}

它只会将 CSS 应用到主体的第一个直接子节点,即 h3。

您可以使用 > 选择器加上 :first-child 来仅定位直接 h3 child.

* {
  margin: 0;
  padding: 0;
}

.test {
  background-color: #cccccc;
  margin: 10px;
  padding: 10px;
}

.test > h3:first-child { color: red; }
<div class="test">
  <h3>Targeted h3</h3>
  <p>Paragraph</p>
  <h3>h3 not targeted</h3>
</div>

<div class="test">
  <p>Paragraph</p>
  <h3>h3 not targeted because of the p tag</h3>
  <h3>h3 not targeted</h3>
</div>