html { scroll-behavior: smooth } 必须写在 html 元素上才生效,写在 body 上无效;它仅对根滚动容器(即 html)生效,且只作用于锚点跳转和 scrollIntoView(),不干预手动拖拽或 JS 瞬时滚动。

html { scroll-behavior: smooth } 必须写在 html 上,写 body 无效
平滑滚动不是 :target 的能力,而是 scroll-behavior 的职责。它只对根滚动容器生效,而浏览器视口的根容器是 html 元素,不是 body。
常见错误是把样式写成:body { scroll-behavior: smooth; }——这在所有主流浏览器里都不起作用。
- ✅ 正确写法:
html { scroll-behavior: smooth; } - ⚠️ 注意:该属性仅影响程序化滚动(锚点跳转、
scrollIntoView()),不影响用户手动拖拽滚动条 - ❌ 如果页面已有 JS 滚动逻辑(比如封装了
scrollTo),需确认没覆盖或重置该 CSS 行为
:target 样式不生效?先查 ID 合法性与匹配精度
:target 是纯字符串精确匹配,不带容错。以下任一条件不满足,样式就“静默失效”:
- ID 不能以数字开头:
<section id="1section">→#1section:target永远不触发 - ID 区分大小写:
#FAQ不会匹配<div id="faq"> - ID 不能含空格、中文、点号(
.)、冒号(:)等非法字符;id="user.profile"会导致#user.profile:target失效(CSS 里点号是 class 选择器,无法转义) - ID 必须全局唯一——重复 ID 会让浏览器随机匹配第一个,
:target行为不可预测
:target 配动画必须提前声明 transition,不能只写在 :target 里
:target 是离散状态(有 / 无),没有中间态,所以只在 :target 规则里写 transition 是无效的。
立即学习“前端免费学习笔记(深入)”;
正确做法是把过渡属性写在基础选择器上,让元素始终具备可过渡能力:
section {
opacity: 0.9;
transform: translateY(0);
transition: opacity 0.3s ease, transform 0.3s ease;
}
section:target {
opacity: 1;
transform: translateY(-4px);
}
- ❌ 错误:
section:target { transition: background-color 0.3s; background-color: #ffeb3b; } - ✅ 正确:基础样式里定义
transition,:target只负责触发终态变化 - 优先用
transform和opacity做动画,避免触发布局重排(height、margin等)
固定导航栏遮住目标内容?用 scroll-margin-top 微调定位
平滑滚动后,目标元素默认贴顶显示,常被 position: fixed 的顶部导航栏盖住。这不是 :target 的问题,而是滚动锚点偏移没调好。
- 给目标元素加
scroll-margin-top,例如:h2:target { scroll-margin-top: 64px; } - iOS Safari ≤15.4 对
scroll-margin-top支持不稳定,可降级用padding-top+ 负margin-top模拟 - 注意:该偏移值需和导航栏实际高度一致,建议用 CSS 自定义变量统一维护
:target 永远“看不见”那个元素。这种情况下,CSS 方案已失效,必须用 JS 监听 hashchange 手动补滚动或样式。


















