【问题标题】:Inheriting Font Family with css variable not working使用 css 变量继承字体系列不起作用
【发布时间】:2022-11-26 01:09:35
【问题描述】:

我正在尝试在变量中继承全局字体系列。但是,这不起作用。

:root {
  --special-font: sans-serif;
}

html {
  font-family: serif;
}

.highlight {
  font-family: var(--special-font);
}

.special {
  --special-font: inherit;
}


/* .special {
  --special-font: serif;
} */


/* .special .highlight {
  font-family: inherit;
} */
<html>

<body>
  <div>
    <p>
      Standard Font: Serif
    </p>
    <p class="highlight">
      Highlight Font: Sans Serif
    </p>
  </div>
  <div class="special">
    <p class="highlight">
      Special Highlight: should be Serif
    </p>
  </div>
</body>

</html>

注释掉的规则都可以使用。但我宁愿不重复自己。有什么我想念的吗?

【问题讨论】:

  • 当您设置一个变量时,您以后不能再给它赋值。创建 2 个变量,如 --standard-font--highlight-font 并只使用 font-family: 变量。 `:root { --special-font: sans-serif; --衬线字体:衬线; } html { font-family: var(--serif-font); } .highlight { font-family: var(--special-font); } .special .highlight { font-family: var(--serif-font); }``
  • 抱歉错误的代码格式
  • @AlexandraBatrak 那将是一种解决方法。但这是不正确的,以后不能更改变量。如果我在 .special 选择器中指定 serif 而不是 inherit,它会按预期工作。
  • 你是对的 :D 它适用于.special { --special-font: initial; }

标签: css css-variables


【解决方案1】:

感谢this questionthis answer 的评论,弄清楚发生了什么。我实际上并没有将变量设置为包含值inherit,而是告诉变量继承它的值。

为了让我的字体系列继承文档范围的字体,我可以将变量设置为initial。对于变量这是一个空字符串,从而将我段落的font-family属性设置为其默认行为,即@ 987654326@。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-05
    • 2021-11-21
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多