CSS 链接样式
学习链接的四种状态 :link/:visited/:hover/:active · 难度:进阶 · +15XP
CSS 链接样式完全指南
链接(<a>)是网页中最基础也最重要的交互元素。通过 CSS 可以为链接的不同状态设置不同样式,从而提升用户体验和可访问性。
链接的四种状态(LVHA 顺序)
CSS 通过伪类选择链接的不同状态。必须按照 LVHA 顺序书写,否则可能出现样式覆盖问题:
| 伪类 | 含义 | 顺序 |
|---|---|---|
:link | 未访问过的链接 | 第 1 位 (L) |
:visited | 用户已访问过的链接 | 第 2 位 (V) |
:hover | 鼠标悬停时 | 第 3 位 (H) |
:active | 鼠标点击按住时 | 第 4 位 (A) |
/* L — Link */
a:link { color: blue; text-decoration: none; }
/* V — Visited */
a:visited { color: purple; }
/* H — Hover */
a:hover { color: red; text-decoration: underline; }
/* A — Active */
a:active { color: orange; }
基础链接样式
a {
color: #2196F3;
text-decoration: none;
transition: all 0.3s ease;
}
a:hover {
color: #1976D2;
text-decoration: underline;
}
链接作为按钮
将链接美化成按钮样式是常见的 UI 需求:
.btn-link {
display: inline-block;
padding: 12px 24px;
background: #4CAF50;
color: white;
border-radius: 4px;
text-decoration: none;
font-weight: bold;
transition: all 0.3s;
}
.btn-link:hover {
background: #45a049;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}
下划线动画效果
.underline-link {
position: relative;
text-decoration: none;
color: #333;
}
.underline-link::after {
content: '';
position: absolute;
bottom: -2px;
left: 0;
width: 0;
height: 2px;
background: #2196F3;
transition: width 0.3s;
}
.underline-link:hover::after {
width: 100%;
}
链接图标
可以为不同类型链接添加图标提示:
a[href$=".pdf"]::after {
content: " (PDF)";
font-size: 0.8em;
color: #999;
}
a[target="_blank"]::after {
content: " ↗";
font-size: 0.8em;
}
a[href^="mailto:"]::before {
content: "✉ ";
}
去除链接默认样式
在导航栏等场景中,通常需要完全重置链接样式:
nav a {
color: inherit; /* 继承父元素颜色 */
text-decoration: none; /* 去除下划线 */
cursor: pointer;
}
nav a:visited {
color: inherit; /* 保持访问后颜色一致 */
}
可访问性注意事项
- 区分链接和普通文本:链接应该有明显的视觉提示(颜色、下划线等)
- 焦点样式:使用
:focus提供键盘导航可见的轮廓 - 足够的点击区域:移动端链接至少 44x44px
- 明确的 hover 反馈:让用户知道元素可交互
a:focus {
outline: 2px solid #4A90D9;
outline-offset: 2px;
}
/* 组合写法 — LVHA + Focus */
a:link, a:visited { color: blue; }
a:hover, a:focus { color: red; }
a:active { color: darkred; }
好的链接样式不仅提升美观度,更是网站可用性和无障碍访问的重要组成部分。