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

标签 html css letter-spacing

我的问题与这个问题基本相同,只是将“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 */
}

我知道它不起作用的原因是计算值而不是指定值是继承的,所以每次 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;
}

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

最佳答案

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 将根据每个元素的字体大小在本地进行解析。

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

关于html - 是否可以相对于字体大小设置字母间距并正确继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47903001/

相关文章:

javascript - DC.js 等值线 map CSS 与颜色冲突,没有 map 显示。如何关闭填充:none?

css - 无法更改输入表单宽度

css - 新开发的 Joomla 空白模板?

css - 使用 css 动画淡出 span 会留下空间

html - 跨浏览器字母间距

html - 某些 CSS 加载因屏幕分辨率而异

javascript - 在转换后的 div 中防止图像失真?

javascript - CSS(多 ID)+(类)的正确语法是什么

Jquery Waypoints 没有检测视口(viewport)

android - 有没有办法修复 EditText 中的字母宽度?