【问题标题】:Avoid CSS styling between certain adjacent elements and classes避免某些相邻元素和类之间的 CSS 样式
【发布时间】:2019-01-28 15:58:45
【问题描述】:

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

向所有标题添加padding-top 会在标题前面有正文但标题之间有不需要的填充时提供所需的填充:

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


更新: 对于同样使用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 也是如此。这就是上面的目标。其他文档中的结构可能有所不同,请自行查看。

【问题讨论】:

  • 查看 w3schools.com 中的 css 选择器以获取更多想法

标签: css r-markdown knitr padding html-heading


【解决方案1】:

怎么样

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

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

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

【讨论】:

  • 没有。它不会起作用,因为这意味着 h3 是一个直接的孩子。并不是说它之前没有兄弟 h2。
  • 这取决于 html,如果没有看到更多内容,很难判断它是否会起作用。想要的布局可能是 body h3 和不需要的布局 body h2+h3
【解决方案2】:

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

* {
  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>

【讨论】:

  • 谢谢!事实证明,在我的情况下,正确的解决方案更复杂,.level2 &gt; .level3:nth-child(3) &gt; h3,但如果没有这些指向选择器&gt;:first-child 的答案,我就不会弄明白。你的回答对这个效果特别有启发。
【解决方案3】:

试试这个:

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

它只会将 CSS 应用于 body 的第一个直接子元素,即 h3。

【讨论】:

    猜你喜欢
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    • 2012-08-03
    • 1970-01-01
    • 2012-06-21
    • 2011-10-20
    相关资源
    最近更新 更多