是否可以相对于字体大小设置字母间距并正确继承?

Is it possible to have letter-spacing relative to the font-size and inherit properly?

我的问题和这个基本一样,只是把"line-height"换成了"letter-spacing":When a relative line-height is inherited, it is not relative to the element's font-size. Why? And how do i make it relative?

我的用例是这样的:

body {
    font-size: 18px;
    letter-spacing: 1.2em; /* I would like letter-spacing to be relative to the font-size across the document, at least until I override it */
}

.small {
    font-size: 14px;
    /* letter-spacing is 1.2em of 18px instead of 14px */
}

我知道它不起作用的原因是计算值而不是指定值是继承的,所以每次 [=15= 时我都必须重新指定 letter-spacing ] 变化。但我希望有一些类似于 line-height 中无单位值的工作方式。

我当然可以:

* {
    letter-spacing: 1.2em;
}

但是我无法在某些元素上停止级联,就像我可以使用 line-height:

body {
    font-size: 18px;
    line-height: 1.5;
}

.normal-line-height {
    line-height: normal;
    /* all the descendants of this element will have a normal line-height */
}

我的意思是,当然,我总是可以做到这一点...

.normal-letter-spacing, .normal-letter-spacing * {
    letter-spacing: normal;
}

但它仍然没有我想要的那么优雅。我不认为这个问题有一个优雅的解决方案,但我想问一下以防我遗漏了什么。

我会尝试使用 REM 而不是 EM 来冻结您与一个值的关系,该值将是根(正文)字体大小。以后你就不用关心字体大小的变化了。

如果您想在更多地方使用 rems,我建议您将所有 classes 组织在一个地方,这样维护起来就不会有太大问题。将它作为实用程序 class 保留也是一个好主意,就像

.txt-spacing-big { letter-spacing: 2rem; }
.txt-spacing-medium { letter-spacing: 1rem; }

CSS 变量没有得到广泛支持,但可以解决问题:

body {
  font-size: 18px;
  --spacing: 1.2em;
}
.normal-letter-spacing { /* No need to select `.normal-letter-spacing *` */
  --spacing: normal;
}
body * {
  letter-spacing: var(--spacing);
}
.small {
  font-size: 14px;
}
<div>
  <p>Lorem ipsum</p>
  <p class="small">Lorem ipsum</p>
</div>
<hr />
<div class="normal-letter-spacing">
  <p>Lorem ipsum</p>
  <p class="small">Lorem ipsum</p>
</div>

它们起作用是因为 custom property 的值计算为指定值:

Computed value: specified value with variables substituted (but see prose for "invalid variables")

因此,与 letter-spacing 不同,1.2em 不会转换为绝对长度。

然后,你可以告诉所有元素使用--spacing作为letter-spacing的值。因此 1.2em 将根据每个元素的字体大小在本地进行解析。

* { letter-spacing: 1.2em; } 不同,此方法仅在 body 中设置 --spacing: 1.2em 一次,并让它通过继承传播。因此,如果你想改变子树中的那个值,你只需要覆盖根中的 --spacing 。您不必 select 所有子树。