我想使用 CSS 在所有标题后面放置一个空格。像这样:
如果 h1 = 在后面添加一个空格
否则如果 h1 + h2 = 在“also”后面添加一个空格,但中间没有空格
这是我的 HTML 代码
<article>
<h1>Title 1</h1>
...
</article>
<article>
<h1>Title 1</h1>
<h2>Title 2</h2>
...
</article>
对于CSS
h1, h2 { padding-bottom: 20px; }
问题是,h1 和 h2 之间也有一个空格。我尝试了下面的代码,但只有那些带有 h1 和 h2 的文章后面有一个空格。
h1 + h2 { padding-bottom: 20px;}
有办法做到这一点吗?或者我应该在 CSS 中使用 h1 + h2 并仅为 h1 添加 < br > ?
最佳答案
有几种方法可以做到这一点,但没有一种方法很漂亮。
/* #1 */
h1 + *:not(h2),
h2 + *:not(h3) { /* etc */
padding-top: 20px;
}
/* #2 */
h1, h2 {
padding-bottom: 20px;
}
h1 + h2 {
margin-top: -20px;
}
(以及这些的变体。)
问题是目前无法选择“向后”,即根据元素后面出现的内容将样式应用于元素。只能使用 +
选择“转发”。或~
sibling combinators 。因此您无法覆盖 <h1>
上的样式基于后续 <h2>
的存在.
在CSS4选择器草案中,有一种指定选择器主题的方法,using the $
sign 。在这种情况下,代码将如下所示:
h1, h2 {
padding-bottom: 20px;
}
$h1 + h2 {
padding-bottom: 0;
}
/* or even */
h1:not($h1 + h2), h2 {
padding-bottom: 20px;
}
但是,目前任何浏览器均不支持此功能。
关于CSS: "AND"和 + 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9781702/