CSS如何增大超链接文本与hover状态下下划线的间距
超链接hover时调整下划线与文本间距的CSS实现方案
方案1:使用原生text-underline-offset属性(推荐)
该属性是CSS Text Decoration Module Level 4新增的特性,专门用于控制text-decoration生成的下划线和文本基线的距离,无需额外模拟元素,代码最简洁。
- 基础用法示例:
a { text-decoration: underline; /* 默认状态下的下划线间距,可按需调整 */ text-underline-offset: 2px; transition: text-underline-offset 0.2s ease; /* 添加过渡动画交互更丝滑 */ } a:hover { /* hover状态下增大间距 */ text-underline-offset: 6px; }
- 兼容情况:支持Chrome 87+、Firefox 70+、Safari 12.1+,覆盖绝大多数现代浏览器使用场景。
方案2:模拟下划线实现(兼容旧浏览器)
如果需要适配更低版本的浏览器,可以放弃原生下划线,改用边框/阴影模拟,灵活调整间距:
用border-bottom模拟
a { text-decoration: none; /* 关闭原生下划线 */ padding-bottom: 2px; /* 控制文本和下划线的默认间距 */ border-bottom: 1px solid currentColor; /* 用边框模拟下划线,currentColor自动继承文本颜色 */ transition: padding-bottom 0.2s ease; } a:hover { padding-bottom: 6px; /* 增大padding即可拉开下划线和文本的距离 */ }
如果不想改变元素高度影响周边布局,可以改用box-shadow模拟:
a { text-decoration: none; box-shadow: 0 2px 0 0 currentColor; /* 第二个参数控制下划线垂直位置,数值越大距离越远 */ transition: box-shadow 0.2s ease; } a:hover { box-shadow: 0 6px 0 0 currentColor; }
内容的提问来源于stack exchange,提问作者Prem Kumar
相关产品推荐
相关产品推荐

