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)
但它仍然没有我想要的那么优雅.我不认为这个问题有一个优雅的解决方案,但我会问我以防错过什么.
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在根中重写即可。您不必选择所有子树。