You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用CSS实现默认最细、hover时增1设备像素的链接下划线?

实现跨DPI设备的差异化下划线效果

可行,通过结合CSS媒体查询与变量,可以实现“默认1物理像素下划线,hover时增加1物理像素”的效果,适配所有DPI设备。

方案1:使用text-decoration(现代浏览器首选)

利用text-decoration-thickness属性配合min-resolution媒体查询,区分不同DPI设备设置下划线厚度:

:root {
  /* 低DPI设备(1x):默认1物理像素,hover增量1物理像素 */
  --underline-base: 1px;
  --hover-increment: 1px;
}

/* 2倍DPI设备(如Retina显示器) */
@media (min-resolution: 2dppx) {
  :root {
    --underline-base: 0.5px; /* 对应1物理像素 */
    --hover-increment: 0.5px; /* 对应增加1物理像素 */
  }
}

/* 3倍DPI设备(如部分高端移动设备) */
@media (min-resolution: 3dppx) {
  :root {
    --underline-base: 0.333px; /* 近似1物理像素 */
    --hover-increment: 0.333px; /* 近似增加1物理像素 */
  }
}

a {
  text-decoration: underline solid currentcolor var(--underline-base);
  text-underline-offset: 0.2em; /* 可选:调整下划线与文本的间距 */
}

a:hover {
  text-decoration-thickness: calc(var(--underline-base) + var(--hover-increment));
}

方案2:使用border-bottom(兼容旧浏览器)

如果需要兼容不支持text-decoration-thickness的旧浏览器,可以用边框模拟下划线:

:root {
  --underline-base: 1px;
  --hover-increment: 1px;
}

@media (min-resolution: 2dppx) {
  :root {
    --underline-base: 0.5px;
    --hover-increment: 0.5px;
  }
}

@media (min-resolution: 3dppx) {
  :root {
    --underline-base: 0.333px;
    --hover-increment: 0.333px;
  }
}

a {
  text-decoration: none;
  border-bottom: var(--underline-base) solid currentcolor;
  padding-bottom: 0.1em; /* 调整下划线与文本的间距 */
}

a:hover {
  border-bottom-width: calc(var(--underline-base) + var(--hover-increment));
}

效果说明

  • 低DPI设备(如常规1080p显示器):默认下划线为1物理像素,hover时变为2物理像素,视觉差异明显。
  • 高DPI设备(如2倍Retina显示器):默认下划线为1物理像素(对应0.5CSS像素),hover时变为2物理像素(对应1CSS像素),符合你的原始预期。

内容的提问来源于stack exchange,提问作者Max

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 21:22:34