如何为Safari实现ascent-override与descent-override的兼容方案?
兼容Safari的多字体垂直对齐方案
问题背景
我在同一行使用三种字体:Inter、Fira Code,以及用<span>单独包裹的Emoji字体(因为Inter自带部分心形等emoji字形,需单独指定emoji字体避免冲突)。为了让三种字体的垂直布局和高亮背景色完全对齐,我通过CSS的ascent-override和descent-override属性,将所有字体的ascent/descent比例统一为Inter的标准(ascent=2728,descent=680,对应ascent-override:100%,descent-override:19.953%)。
这套方案在Chrome中正常工作,但Safari不支持ascent-override和descent-override,导致同一行的字体垂直错位、高亮背景不统一。
兼容方案
方案1:CSS降级调整(无需修改字体文件)
如果不想修改字体文件,可以通过line-height和vertical-align属性做兼容调整:
- 给包含多字体的父元素设置固定
line-height,值匹配目标字体的行高(比如基于Inter的ascent+descent计算:(2728+680)/1000 = 3.408,对应line-height:3.408,需根据实际字体大小微调)。 - 对每个字体的
<span>设置vertical-align: middle或精确数值调整(比如vertical-align: -0.1em),手动对齐基线和高度。
缺点:需要针对不同字体大小、Safari版本做适配,精度不如字体文件修改。
方案2:修改字体文件(彻底解决对齐问题)
根据观察到的「Apple Color Emoji与Fira Code的ascent/descent比例相同」,只需修改Inter字体文件的ascent和descent值,让它和另外两种字体匹配,就能在Safari中实现原生对齐。
操作步骤:
- 下载Inter字体文件:从官方渠道获取Inter的原始TTF格式字体文件。
- 使用字体编辑工具修改:
- 推荐工具:FontForge(免费开源)、Glyphs(Mac端付费工具)。
- 打开Inter字体文件,找到字体的「OS/2表」和「hhea表」:
- 在FontForge中,依次点击
Element > Font Info > OS/2,调整Win Ascent和Win Descent值,使其匹配Fira Code的ascent/descent比例。 - 同步调整
hhea Ascent和hhea Descent,确保与OS/2表数值对应,避免布局异常。
- 在FontForge中,依次点击
- 导出修改后的字体:导出为WOFF2格式(Web最优格式),替换原CSS中Inter的字体源。
- 移除CSS中的强制覆盖属性:现在字体本身的ascent/descent已经统一,无需保留
ascent-override和descent-override。
修改后的CSS示例:
@font-face { font-family: 'Fira Code'; font-style: normal; font-weight: 300 700; font-display: swap; src: url(https://fonts.gstatic.com/s/firacode/v22/uU9NCBsR6Z2vfE9aq3bh3dSDqFGedA.woff2) format('woff2'); } @font-face { font-family: 'Inter'; font-style: normal; font-weight: 100 900; font-display: swap; src: url('/path/to/modified-inter.woff2') format('woff2'); /* 替换为修改后的字体路径 */ } @font-face { font-family: Emoji; src: local("Apple Color Emoji"), local("Segoe UI Emoji"), local("NotoColorEmoji"), local("Noto Color Emoji"), local("Segoe UI Symbol"), local("Android Emoji"), local("EmojiSymbols"); } p { font-size: 100px; line-height: 3.408; /* 可选,基于字体ascent+descent的行高 */ } .inter { font-family: Inter; background-color: tomato; } .fira-code { font-family: Fira Code; background-color: tomato; } .emoji { font-family: Emoji; background-color: tomato; }
注意事项:
- 不要修改系统字体(比如Apple Color Emoji),一是系统字体路径有权限限制,二是修改后会影响全局系统显示。
- 确保修改后的字体符合原字体的开源协议(Inter采用SIL Open Font License,允许修改和分发)。
验证效果
修改后,Chrome依然能正常显示(字体本身属性已对齐,无需CSS覆盖),Safari会自动使用字体文件的原生ascent/descent值,实现三种字体的垂直布局和高亮背景完全一致。
内容的提问来源于stack exchange,提问作者Calebmer
相关产品推荐
相关产品推荐

