你每次给文字加下划线都要跟设计师来回拉锯——今天 CSS 用一个属性把这件事彻底原生化了

写给文字加下划线的时候,你有没有注意过 g、y、p、q 这些字母的下沿,划线是直接穿过去的?

这是 CSS text-decoration 几十年的默认行为。设计上想要一条干净的线,用户只能靠两三种 workaround 硬撑:要么用 linear-gradient 背景模拟、要么加 ::after 伪元素、要么整个元素套一层 <span> 再微调。现在 Chrome 154 用一个 CSS 属性把这件事彻底原生化了。

这个属性叫 text-decoration-inset,控制下划线/删除线/上划线与文字边缘的间距——正值往里缩、负值往外扩、auto 让浏览器根据字体 metrics 自动判断。Chrome 154 正式支持,Firefox 146 已稳定,Safari 暂时不支持百分比值但基础功能已在路上。

两行代码就能解决问题:

/* 基础用法:让下划线往里收,不穿过 descender */
p {
  text-decoration: underline;
  text-decoration-inset: 0.1em; /* 推荐值 */
}

/* auto 模式:浏览器根据字体自动计算,gap 更自然 */
p {
  text-decoration: underline;
  text-decoration-inset: auto;
}

/* 双值语法:开头和结尾可以不同间距 */
p {
  text-decoration: underline;
  text-decoration-inset: 0.1em 0.05em;
}

对比一下以前的 workaround:

/* 方案一:linear-gradient 背景模拟(脆弱,每次改颜色都要改两处) */
p {
  background: linear-gradient(transparent 70%, white 70%) padding-box;
  /* 完全不能响应 hover 状态 */
}

/* 方案二:::after 伪元素(侵入性强,影响布局) */
p::after {
  content: '';
  position: absolute;
  left: 0; right: 0;
  bottom: 0.25em;
  height: 1px;
  background: currentColor;
}

text-decoration-inset 是 CSS Text Decoration Level 4 规范里的属性,一次声明、浏览器原生渲染,不影响布局、不需要额外元素。

落地方便,直接在现有 text-decoration 附近加一行即可。如果要兼容暂不支持的浏览器,可以用 @supports 做渐进增强:

p {
  text-decoration: underline;
}
@supports (text-decoration-inset: auto) {
  p {
    text-decoration-inset: auto;
  }
}

全球兼容性:Firefox 146+ 稳定支持,Chrome 154+ 正式支持,Safari 基础值支持但百分比值尚在推进。现在可以在生产项目里用了。

评论区

0 条评论

登录后可评论。

小鹿·界面实验室 2533 阅读