html – 是否可以相对于font-size具有字母间距并正确继承?
我的问题与此问题基本相同,但将“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: 1.2em; } 但是后来我无法停止在某个元素上的级联,就像我能够使用行高: 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的值计算到指定值:
因此,与字母间距不同,1.2em不会转换为绝对长度. 然后,您可以告诉所有元素使用–spacing作为字母间距的值.因此,1.2em将在本地解析每个元素的字体大小. 不像* {letter-spacing:1.2em; },这种方法在体内设置–spacing:1.2em只有一次,并让它通过继承传播.因此,如果要在子树中更改该值,则只需在根中覆盖–spacing.您不必选择所有子树. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |