7

我的问题与这个问题基本相同,但将“line-height”替换为“letter-spacing”:当继承相对 line-height 时,它与元素的 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 */
}

我知道它不起作用的原因是计算值而不是指定值是继承的,所以我必须在letter-spacing每次font-size更改时重新指定。但我希望有一些类似于无单位价值观的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;
}

但它仍然没有我想要的那么优雅。我不认为这个问题有一个优雅的解决方案,但我问的是我是否遗漏了一些东西。

4

2 回答 2

4

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>

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

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

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

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

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

于 2016-09-30T14:12:43.127 回答
-1

我会尝试在 EM 上使用 REM 来冻结你与一个值的关系,这将是根(正文)字体大小。您以后不必关心字体大小的更改。

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

.txt-spacing-big { letter-spacing: 2rem; }
.txt-spacing-medium { letter-spacing: 1rem; }
于 2016-09-30T14:03:25.807 回答