使用 rem 在 :root 元素中设置字体大小有效。为什么?

Using rem to set font-size inside :root element works. Why?

我最近 运行 发现以下代码非常有效:

:root {
  font-size: .8rem;
}

(即重新缩放默认大小)。

我的问题是:为什么这样做有效?我认为在 :root 中使用 rem 应该是非法的或定义错误的(因为 rem 被定义为相对于 :root 的字体大小本身——所以使用 rem 来定义 :root的属性至少很奇怪)。

谢谢!

P.S。这有点 'meta question' 理解 CSS 背后的计算机制。我非常确定执行此操作的规范方法是在根元素上设置百分比大小 (a.k.a。<html>)。

rem 值是相对于根元素的 font-size 属性 的,对于 HTML 文档是 html 元素。

根据 CSS Values and Units Module Level 3 关于 rem 值:

Equal to the computed value of font-size on the root element. When specified on the font-size property of the root element, the rem units refer to the property’s initial value

如果没有在根元素上设置明确的值,它会从用户可以更改的浏览器设置中继承它的值;通常浏览器设置中的默认字体大小为 16px 或中号。

因此,如果您在根元素上设置 rem,您是在相对于浏览器设置中的默认值设置它