响应式导航:不写 JS 也能用
吸顶、横滑、当前项高亮、键盘可达——用纯 CSS 做一个在手机上比汉堡菜单更好用的导航。
汉堡菜单被滥用很多年了:多一次点击、藏起信息、还要写一堆 JS 和焦点管理。如果导航项不超过八个,横向滚动是更好的方案——不用点开、不遮内容、零 JS。
结构#
<header class="head">
<a class="brand" href="/">css教程网</a>
<nav class="nav" aria-label="主导航">
<a href="/basics/" class="on">基础</a>
<a href="/layout/">布局</a>
<a href="/modern/">现代 CSS</a>
<a href="/recipes/">实战</a>
<a href="/snippets/">片段库</a>
<a href="/reference/">速查</a>
</nav>
</header>桌面:等距排列 + 当前项高亮#
.head {
position: sticky; top: 0; z-index: 40;
display: flex; align-items: center; gap: 24px;
height: 64px; padding: 0 24px;
background: rgb(255 255 255 / .88);
backdrop-filter: blur(14px);
border-bottom: 1px solid #e5e9f0;
}
.nav { display: flex; gap: 2px; overflow-x: auto; scrollbar-width: none; }
.nav::-webkit-scrollbar { display: none; }
.nav a {
padding: 8px 12px; border-radius: 8px;
font-size: 14.5px; color: #2f3846; white-space: nowrap;
}
.nav a:hover { background: #eef2f9; }
.nav a.on { color: #2b57ff; background: #edf1ff; font-weight: 600; }white-space: nowrap 不能漏,否则窄屏下文字会折成两行,导航高度乱掉。
移动端:整条横滑#
@media (max-width: 720px) {
.head { height: auto; flex-wrap: wrap; padding: 10px 16px 0; gap: 6px; }
.nav { order: 3; flex-basis: 100%; padding-bottom: 8px; margin-inline: -16px; padding-inline: 16px; }
.nav a { padding: 6px 10px; font-size: 13.5px; }
}margin-inline: -16px 加 padding-inline: 16px 是让滚动区域贴到屏幕边缘,滚动时第一个和最后一个项目不会突然被裁一半。这是横滑列表的标准技巧。
滚动时的视觉提示#
横滑最大的问题是用户不知道右边还有内容。两个纯 CSS 方案:
/* 1. 右侧渐隐,暗示还有内容 */
.nav { mask-image: linear-gradient(90deg, #000 0, #000 calc(100% - 24px), transparent 100%); }
/* 2. 滚动吸附,让每次滑动停在项目边界 */
.nav { scroll-snap-type: x proximity; }
.nav a { scroll-snap-align: start; }当前项:服务端标记最可靠#
用 JS 根据 URL 加 .on 会有闪烁,而且首屏可能高亮错误。在服务端渲染时直接输出 class 最稳:
<a href="/basics/" class="<?= $active === 'basics' ? 'on' : '' ?>">基础</a>如果做不到服务端标记,用 aria-current="page" 配合属性选择器也可以:
.nav a[aria-current="page"] { color: #2b57ff; background: #edf1ff; }键盘可达性检查清单#
- Tab 能依次走到每一项,焦点框清晰可见。
- 不要用
outline: none却不给替代样式。 - 导航外层加
<nav aria-label="主导航">,读屏能跳过。 - 跳过导航链接(skip link)放在 DOM 最前面,聚焦时显示。