我在 HTML 和 SCSS 中有以下设置 -
h1 {
margin-bottom: 24px;
+ p {
margin-top: 0;
}
}
p {
margin-bottom: 24px;
}
<h1>Main title</h1>
<p>Sub-title goes there here</p>
我想要实现的是,我想要 <h1>
的 margin-bottom
从 24p
更改x 到 0px
当有<p>
在它后面标记,但如果没有 <p>
标签,然后是 margin-bottom
在<h1>
将保留 24px
.
我尝试使用 &
运算符,但我似乎无法理解它。
h1 {
margin-bottom: 24px;
& + {
margin-bottom: 0;
}
+ p {
margin-top: 0;
}
}
p {
margin-bottom: 24px;
}
你觉得我应该怎么做?我需要使用 @if
吗?针对这种情况的指令?
最佳答案
由于 CSS 的工作方式,这是不可能的
您想要实现的目标最终是不可能的。 SASS 编译成 CSS,它只在一个方向上遍历。这意味着您可以定位前面有另一个元素的元素,但不能选择后面有另一个元素的元素。
你能做什么?
鉴于此限制,实现结果的最合适方法是更改逻辑,以便将 h1
上的 margin-bottom
替换为 margin -top
在 p
标签上。
SASS
h1 {
margin-bottom: 0;
+ p {
margin-top: 0;
}
}
p {
margin-top: 24px;
}
编译示例
h1 {
margin-bottom: 0;
}
h1 + p {
margin-top: 0;
}
p {
margin-top: 24px;
}
<h1>Main title</h1>
<p>Sub-title goes there here</p>
如果您不能将 margin
从 h1
移动到 p
标签,则可以使用负数
偏移 p
上的 margin-toph1
上的 margin-bottom
。
SASS
h1 {
margin-bottom: 24px;
+ p {
margin-top: -24px;
}
}
p {
margin-top: 24px;
}
编译示例
h1 {
margin-bottom: 24px;
}
h1 + p {
margin-top: -24px;
}
p {
margin-top: 24px;
}
<h1>Main title</h1>
<p>Sub-title goes there here</p>
关于html - (SCSS)根据后续元素的状态更改前面元素的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41868842/