每次 sticky 导航栏贴上去了我都不知道,除非写个监听——今天这件事被 CSS 彻底原生化了

每次想要在 sticky 导航栏贴顶时加个阴影,你通常得先写一个 IntersectionObserver,监听一个看不见的 1px 元素,再等回调触发再 toggle class。这套流程谁都写过,但它从来不是 CSS 的问题——CSS 从来没有机会去管这件事。

Chrome 133 给了这个机会。

@container scroll-state(stuck: top) 是 CSS Scroll-State Queries 规范里的一个查询函数。它的作用很直接:查询「这个滚动容器里,有没有哪个 sticky 元素贴到了指定边缘」。浏览器替 CSS 把这件事管了起来,不需要 JavaScript 反复计算偏移量。

核心用法就两行:

.scroll-wrap {
  container-type: scroll-state;
}
@container scroll-state(stuck: top) {
  .nav {
    box-shadow: 0 2px 8px rgb(0 0 0 / 15%);
  }
}

当 .nav 作为 sticky 元素贴到滚动容器顶部时,.scroll-wrap 的 @container scroll-state(stuck: top) 条件成立,阴影自动加上。浏览器自己在内部追踪这个状态,滚动过程中没有任何 JavaScript 被调用。

这个 API 的工作方式有一个需要特别注意的点:scroll-state(stuck: top) 的样式是作用于 sticky 元素的后代,不是 sticky 元素本身。所以实战里通常需要包一层,或者把 container-type 设在外层父级上:

/* 推荐结构:外层设为 scroll-state 容器 */
.page-scroll {
  container-type: scroll-state;
}
/* 检测 nav 的 sticky 状态,给它的子元素加样式 */
@container scroll-state(stuck: top) {
  nav {
    background: white;
    box-shadow: 0 2px 12px rgb(0 0 0 / 12%);
  }
}

如果你还在用 IntersectionObserver 方案做 sticky 检测,切过来几乎不需要改 DOM 结构,只需要把 JS 那套删掉,加上 container-type: scroll-state 和 @container 块。

scroll-state() 家族都能查什么

stuck 只是 scroll-state() 的一种用法。整个规范支持三种查询:

  • scroll-state(stuck: top/bottom/left/right/none) — 查询哪个 sticky 边缘被触发了
  • scroll-state(snapped: x/y/inline/block) — 查询哪个滚动吸附点被激活了
  • scroll-state(scrollable: both/horizontal/vertical) — 查询容器是否还有可滚动内容
  • scroll-state(scrolled: top/bottom/left/right) — 查询用户最后一次滚动到了哪个方向

这意味着 sticky 导航栏的阴影吸附、轮播图当前帧高亮、滚动提示显示隐藏这些常见交互,全都可以用纯 CSS 写了,不需要各自写一个 scroll 监听器。

浏览器支持与渐进增强

目前全球覆盖率约 50%,Chrome 133+ 和 Edge 133+ 完整支持,Safari 16.4+ 和 Firefox 113+ 支持 stuck 查询的核心部分。因为覆盖率还不够,尚未进入 Baseline。

生产环境建议做渐进增强:

/* 先写降级样式 */
.nav {
  background: white;
}
/* 现代浏览器升级 */
@supports (container-type: scroll-state) {
  .page-scroll {
    container-type: scroll-state;
  }
  @container scroll-state(stuck: top) {
    .nav {
      box-shadow: 0 2px 12px rgb(0 0 0 / 12%);
    }
  }
}

下一步

  1. 打开 DevTools,找一个现有的 sticky 导航栏,把 IntersectionObserver 那段删掉
  2. 给外层加 container-type: scroll-state,写一个 @container scroll-state(stuck: top) 块
  3. 填进你的 CSS 设计令牌(颜色、阴影半径),观察滚动时样式自动切换
  4. 跑一遍 Safari 和 Firefox,看看降级是否正常工作

如果你现在写的 sticky 检测还在用 offsetTop + scroll 或 IntersectionObserver,这套流程可以直接删掉了。CSS 已经把这件事管了起来。

评论区

0 条评论

登录后可评论。

小鹿·界面实验室 201 阅读