line-height:1时竖排字母垂直占用高度及背景匹配问题
问题描述
我将文本设置为upright竖排状态,希望每个字母背后显示不同background,实际场景中背景列表由接收字母数量的函数随机生成。我使用等宽字体并设置line-height:1,原以为每个字母会占用1lh或1em的垂直空间,但实际并不足够。相关代码如下:
Sass示例代码
$c: #448aff, #1565c0, #009688, #8bc34a, #ffc107, #ff9800, #f44336, #ad1457; $n: length($c); $m: .5*$n; $l: (); @for $i from 0 to $m { $l: $l, conic-gradient(from random(360)*1deg at random(100)*1% random(100)*1%, nth($c, $i + 1), nth($c, $i + $m + 1), nth($c, $i + 1)) 0 $i*1em } div { box-shadow: 0 0 0 6px; background: $l; background-repeat: no-repeat; background-size: 100% 1em; font: 900 clamp(1em, 18vmin, 18em)/ 1 monospace; writing-mode: vertical-lr; text-orientation: upright; text-transform: uppercase }
CSS示例代码
div { box-shadow: 0 0 0 6px; background: conic-gradient(from 37deg at 54% 48%, #448aff, #ffc107, #448aff), conic-gradient(from 264deg at 8% 31%, #1565c0, #ff9800, #1565c0) 0 1em, conic-gradient(from -61deg at 92% 2%, #009688, #f44336, #009688) 0 2em, conic-gradient(from -5deg at 41% 95%, #8bc34a, #ad1457, #8bc34a) 0 3em; background-repeat: no-repeat; background-size: 100% 1em; font: 900 clamp(1em, 18vmin, 18em)/1 monospace; writing-mode: vertical-lr; text-orientation: upright; text-transform: uppercase }
HTML结构
<div>play</div>
要求绝对不能将文本拆分为单个字母包裹元素,现咨询:
- 该场景下字母实际占用的垂直空间是多少?
- 如何调整渐变的尺寸和位置,使每个字母对应独立背景?
解决方案
一、字母实际占用的垂直空间:1ch
在writing-mode: vertical-lr(竖排)+text-orientation: upright(正排文字)的场景下,等宽字体中单个字母的垂直占用空间对应**1ch单位**,而非1em或1lh。
ch原本定义为当前字体中数字"0"的宽度,但在竖排模式下,单位方向会跟随文字流向,此时1ch就代表单个字符的垂直高度——因为文字竖排后,字符的布局方向转为垂直,原本的宽度维度变成了高度维度,刚好匹配等宽字符的实际占用空间。
你之前用的1em是基于字体大小的单位,但等宽字体的字符高度(尤其是大写字母)和1em并不完全匹配,line-height:1仅设置行高,无法精准对应单个字符的实际占位,ch才是适配这个场景的精准单位。
二、调整渐变尺寸和位置的具体方法
只需将代码中所有的1em替换为1ch即可:
- 修改后的Sass代码
$c: #448aff, #1565c0, #009688, #8bc34a, #ffc107, #ff9800, #f44336, #ad1457; $n: length($c); $m: .5*$n; $l: (); @for $i from 0 to $m { $l: $l, conic-gradient(from random(360)*1deg at random(100)*1% random(100)*1%, nth($c, $i + 1), nth($c, $i + $m + 1), nth($c, $i + 1)) 0 $i*1ch // 替换为1ch } div { box-shadow: 0 0 0 6px; background: $l; background-repeat: no-repeat; background-size: 100% 1ch; // 替换为1ch font: 900 clamp(1em, 18vmin, 18em)/ 1 monospace; writing-mode: vertical-lr; text-orientation: upright; text-transform: uppercase }
- 修改后的CSS代码
div { box-shadow: 0 0 0 6px; background: conic-gradient(from 37deg at 54% 48%, #448aff, #ffc107, #448aff), conic-gradient(from 264deg at 8% 31%, #1565c0, #ff9800, #1565c0) 0 1ch, conic-gradient(from -61deg at 92% 2%, #009688, #f44336, #009688) 0 2ch, conic-gradient(from -5deg at 41% 95%, #8bc34a, #ad1457, #8bc34a) 0 3ch; background-repeat: no-repeat; background-size: 100% 1ch; // 替换为1ch font: 900 clamp(1em, 18vmin, 18em)/1 monospace; writing-mode: vertical-lr; text-orientation: upright; text-transform: uppercase }
修改后,每个渐变背景的高度会精准匹配单个竖排字母的垂直占用空间,位置也会对应每个字母的布局,实现每个字母背后显示独立背景的效果。
内容的提问来源于stack exchange,提问作者Ana
相关产品推荐
相关产品推荐

