首页 > 解决方案 > 防止儿童的默认 html 样式被覆盖

问题描述

div {
  height: 400px;
  cursor: pointer;
  font-family: sans-serif;
}
<div>
  div has pointer and sans-serif font
  <p>and paragraph also has it</p>
  <code>but code element doesn't have sans-serif font but pointer.</code>
</div>

p元素默认具有光标text和字体系列。serif两者都被覆盖。
code元素默认具有光标text和字体系列。monospace只有光标已被覆盖。

为什么会这样?在code元素中,font-family不会被覆盖。为什么?如何在某些选定元素中设置默认 html 样式?(pcode这里的元素)

显然,甚至all: revert不起作用!

div {
  height: 400px;
  cursor: pointer;
  font-family: sans-serif;
}

p {
  all: revert;
}

code {
  all: revert;
}
<div>
  div has pointer and sans-serif font
  <p>and paragraph also has it</p>
  <code>but code element doesn't have sans-serif font but pointer.</code>
</div>

all: initial有效,但我不想应用原始的 CSS 实现。我希望应用用户代理样式表规则。我用过revert但没有用。

标签: htmlcssinheritance

解决方案


根据 MDN:

默认情况下,内容文本使用用户代理的默认等宽字体显示。

和:

可以为代码选择器定义 CSS 规则以覆盖浏览器的默认字体。用户设置的首选项可能优先于指定的 CSS。

因此,您确实需要指定具体所需的字体。如果担心正确的设置未结转/将来可能会更改,您可以将其定义为 CSS 变量,因此只需在一处更改其值。

div {
  height: 400px;
  cursor: pointer;
  --font: sans-serif;
  font-family: --font;
}

p {
  all: revert;
}

code {
  all: revert;
  font-family: --font;
  
}
<div>
  div has pointer and sans-serif font
  <p>and paragraph also has it</p>
  <code>and the code element also has sans-serif</code>
</div>


推荐阅读