a 标签默认带下划线,做导航或列表时一般都要去掉。写法就一句,但实际项目里经常出现“写了没生效”。
基本写法
a {
text-decoration: none;
}也可以只关某一种线,写 text-decoration-line: none,效果一样。
为什么写了没生效
最常见的是优先级被覆盖。样式表里如果早有 #nav a { text-decoration: underline; },你后面写 a { text-decoration: none; } 也没用,ID 选择器的优先级更高。打开开发者工具看计算样式,被划掉的声明一眼能看出来。
第二种是伪类单独设置,比如 a:hover、a:visited 里又写了 text-decoration,只改 a 管不到悬停状态。
第三种是继承:下划线来自父元素。给父元素设了 text-decoration: underline,子元素写 none 通常取消不了父级画出来的线,这是规范里的继承特性。解决办法是把下划线从父元素移走。
导航和整站的写法
.nav a,
.nav a:hover,
.nav a:visited {
text-decoration: none;
}
a { text-decoration: none; color: inherit; }color: inherit 让链接跟随周围文字颜色,避免满屏蓝字。
去掉下划线后的可用性
正文链接去掉下划线,用户很难看出是可点的,对无障碍也不友好。推荐正文保留下划线,导航、按钮、卡片这类本身可辨识的链接再去掉。
只想换下划线观感的话,用扩展属性更省事:
a {
text-decoration: underline;
text-decoration-color: #c9d1d9;
text-underline-offset: 4px;
text-decoration-thickness: 1px;
}伪元素模拟下划线
a { position: relative; text-decoration: none; }
a::after {
content: ""; position: absolute;
left: 0; right: 0; bottom: -2px; height: 1px;
background: currentColor;
transform: scaleX(0); transition: transform .2s;
}
a:hover::after { transform: scaleX(1); }适合做悬停动画。行内元素上绝对定位要配合父元素的 position 使用。