html - (SCSS)根据后续元素的状态更改前面元素的属性

标签 html css sass

我在 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-bottom24p 更改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 -topp 标签上。

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>

如果您不能将 marginh1 移动到 p 标签,则可以使用负数 p 上的 margin-top 偏移 h1 上的 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/

相关文章:

html - Wordpress - 链接到 HTML 中的图像不起作用

javascript - 下拉按钮未自定义

javascript - 限制 jQuery slideToggle 处理多个元素

css - SCSS :nth-child mixin with array

css - React - 当父组件收缩时使子组件收缩

python - 列表索引必须是整数,而不是元组

html - 在移动设备上禁用悬停

javascript - 使用 -- 而不是 value = value - 1 无法正确更新 .html

javascript - "position:fixed;bottom:0;"在 iPhone 中不起作用

ruby-on-rails - 尽管有更改,Rails仍使用缓存的application.css