CSS 怎么去掉 a 超链接的下划线?
这个问题看着简单,text-decoration: none 谁都会写。但实际项目里经常出现"写了没生效"——尤其是用组件库、或者链接在 hover、visited 状态下还有下划线的时候。
一、最基本写法
a {
text-decoration: none;
}
一行就够。它会去掉链接默认的下划线,包括 hover 和 visited 状态(因为没单独覆盖)。
二、为什么写了没生效
1. 优先级不够
如果组件库或全局样式里有更具体的选择器,比如 .content a 或者 a.link,你的 a {} 优先级更低,会被覆盖。解决办法是提高选择器权重:
/* 方法一:加类名 */
.nav a { text-decoration: none; }
/* 方法二:用属性选择器提高权重 */
a[href] { text-decoration: none; }
/* 方法三:限定父级 */
body .nav a { text-decoration: none; }
不建议上来就用 !important,后面维护会很痛苦。先 F12 看清是哪个规则生效了。
2. 写在了错误的元素上
下划线可能来自父元素,而不是 a 本身。比如父级 li 设了 text-decoration: underline,子元素 a 设 none 是没用的——text-decoration 的传播规则是父元素的下划线会穿透到子元素,子元素无法通过 none 取消。
要取消,必须把 underline 从父元素上移除,或者给 a 设 display: inline-block,建立独立的盒模型。
3. 用了伪元素画的下划线
有些设计用 a::after 加 border-bottom 模拟下划线,这种 text-decoration: none 管不了,得找 border-bottom 或者 background-image 相关的样式。
4. 浏览器默认样式覆盖
极少数情况下用户样式表或浏览器强制样式会覆盖。可以试 a:link, a:visited, a:hover, a:active 四个状态一起写:
a:link, a:visited, a:hover, a:active {
text-decoration: none;
}
老教程常这么写,现在大多数情况没必要,但遇到诡异问题时能兜底。
三、保留 hover 下划线的做法
很多人想去掉默认下划线,但鼠标悬停时显示,作为可点击的提示:
a {
text-decoration: none;
color: #333;
}
a:hover {
text-decoration: underline;
color: #1677ff;
}
注意 text-decoration 在 hover 上会同时影响子元素,如果 a 里面有 span 或图标,会一起被划线。只想给文字划线的话,用 border-bottom 或者 ::after 更可控:
a {
text-decoration: none;
border-bottom: 1px solid transparent;
}
a:hover {
border-bottom-color: #1677ff;
}
四、text-decoration 的其他值
text-decoration: underline overline line-through; /* 可组合 */
text-decoration-color: red; /* 单独设颜色 */
text-decoration-thickness: 2px; /* 线宽 */
text-underline-offset: 4px; /* 下划线距离文字的距离 */
text-underline-offset 很好用,默认下划线紧贴文字,设置 3-4px 视觉上更舒服。这三个属性现代浏览器都支持,IE 不支持。
五、几个实用场景
导航菜单
菜单项一般是链接,去掉下划线,hover 时改背景色而不是划线:
.nav a {
text-decoration: none;
padding: 10px 16px;
color: #333;
}
.nav a:hover {
background: #f5f5f5;
}
正文里的链接
正文链接建议保留下划线或者用颜色区分,全部去掉会让用户分不清哪里可以点。无障碍规范也建议正文链接不能只靠颜色区分。
卡片整体可点击
a 包住整个卡片,里面文字不能有下划线:
.card-link {
text-decoration: none;
color: inherit;
display: block;
}
color: inherit 让卡片里的文字颜色不被链接默认的蓝色影响。
六、调试建议
F12 选中元素,在 Styles 面板里看 text-decoration 被哪条规则设置了,勾掉试试。Computed 面板能看到最终生效的值。如果 Computed 里是 none 但视觉上还有线,那线就是 border 或者背景图,不是 text-decoration。