是否可以相对于font-size具有字母间距并正确继承?

ben*_*ace 7 html css letter-spacing

我的问题与此问题基本相同,但将"line-height"替换为"letter-spacing":当继承相对行高时,它与元素的font-size无关.为什么?我如何使它相对?

我的用例是这样的:

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 */
}
Run Code Online (Sandbox Code Playgroud)

我知道它不起作用的原因是继承了计算值而不是指定值,因此letter-spacing每次font-size更改时都必须重新指定.但我希望有类似于line-height工作中无单位价值的东西.

当然,我可以这样做:

* {
    letter-spacing: 1.2em;
}
Run Code Online (Sandbox Code Playgroud)

但是我无法阻止某个元素的级联,就像我能够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 */
}
Run Code Online (Sandbox Code Playgroud)

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

.normal-letter-spacing, .normal-letter-spacing * {
    letter-spacing: normal;
}
Run Code Online (Sandbox Code Playgroud)

但它仍然没有我想要的那么优雅.我不认为这个问题有一个优雅的解决方案,但我会问我以防错过什么.

Ori*_*iol 6

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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

它们之所以有效,是因为自定义属性的值计算为指定值:

计算值:用变量替换的指定值(但请参阅散文中的“无效变量”)

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

然后,您可以告诉所有元素用作--spacing的值letter-spacing。因此1.2em将在本地解决每个元素的字体大小。

与 不同* { letter-spacing: 1.2em; },此方法仅在 中设置--spacing: 1.2em一次body,并让它通过继承传播。因此,如果要更改子树中的该值,只需--spacing在根中重写即可。您不必选择所有子树。

  • 是的,我只记得自定义 props 在计算它们的 var() 引用之前被继承。如果没有自定义道具,您实际上无法做到这一点,因此它不仅更干净,而且实际上是当您事先不知道后代时执行此操作的唯一方法(这是问题的关键)。 (3认同)
  • “当然我可以这样做:* { letter-spacing: 1.2em; }” 您只是在做同样的事情,但出于某种原因将值移动到自定义属性...。 (2认同)
  • 很多人看到自定义 props 后会说“这些根本不像 Sass/LESS vars!” 他们是对的。但这并不意味着自定义道具不强大。[另一个例子。](http://stackoverflow.com/questions/25451809/is-there-anything-in-the-css-spec-that-allows-a-percentage-property-to-be-relati/25454155# 25454155) (2认同)