首页 > 解决方案 > 从更通用的选择器继承值

问题描述

定义了以下样式:

h1 {
  margin-bottom: 2em;
}

h1:last-child {
  margin-bottom: 0;
}

如果我有一个 h1 元素,它是我想为其应用普通 h1 元素的 margin-bottom 的最后一个子元素,有没有比为该元素再次显式定义 2em 的 margin-bottom 更好的方法?

非常感谢

标签: css

解决方案


使用 CSS 变量:

h1 {
  margin-bottom: var(--b,2em);
}

h1:last-child {
  --b: 0; /* override the default 2em */
}

h1.custom {
  --b:initial; /* get back to the default 2em*/
}


div {
  border:1px solid;
}
<div>
  <h1>some text</h1>
</div>

<div>
  <h1 class="custom">some text</h1>
</div>


推荐阅读