弹层尺寸跟着锚点跑,滚动的时候还要动——以前要两套工具,现在 CSS 自己全包了
说实话,弹层(tooltip/popover)配了五年,最烦的从来不是「弹出在哪」,是「尺寸怎么办」。
按钮大,弹层就大;按钮小,弹层就小——这件事以前只能靠 JS 算。现在 anchor-size() 直接把锚点元素的尺寸拿过来用了,配合 scroll-driven animations,弹层不仅尺寸跟着锚点跑,滚动的时候还能自动消失,全程不需要一行 JS。
先说 anchor-size() 是什么。
CSS Anchor Positioning 里的一个函数,用来取锚点元素的宽高。配合 width: anchor-size(width) 或 height: anchor-size(height),弹层的尺寸就直接绑到锚点上了。
/* 定义锚点 */
.trigger-btn {
anchor-name: --my-tooltip;
}
/* 弹层尺寸直接引用锚点 */
.tooltip {
position: absolute;
left: anchor(--my-tooltip right);
bottom: anchor(--my-tooltip top);
/* 关键:尺寸跟锚点走 */
width: anchor-size(width);
height: anchor-size(height);
}
按钮多宽,弹层就多宽。不用 getBoundingClientRect(),不用 ResizeObserver,纯 CSS。
再说 scroll-driven animations 怎么把它变得更完整。
弹层跟着锚点跑这件事,到这里已经比原来好了。但还有一层体验问题:页面滚动的时候,弹层还在原位「漂着」,用户体验很割裂。以前要靠 JS 监听滚动事件来隐藏弹层,现在 CSS 自己做。
.tooltip {
/* 绑定滚动时间线 */
animation: hide-on-scroll 0.3s ease-out forwards;
animation-timeline: scroll(root);
}
@keyframes hide-on-scroll {
from {
opacity: 1;
transform: translateY(0);
}
to {
opacity: 0;
transform: translateY(-8px);
pointer-events: none;
}
}
就这么两段。页面一滚动,弹层淡出 + 上移,完全脱离主线程,在合成线程上跑。
两个组合在一起,才是完整解法。
弹层跟着锚点走尺寸,滚动的时候自动消失。以前这套逻辑要:1 个 ResizeObserver 算尺寸 + 1 个 scroll 事件监听隐藏弹层。现在纯 CSS,两件事各管各的,互不干扰。
/* 完整示例 */
.trigger {
anchor-name: --tip;
}
.tooltip {
position: absolute;
left: anchor(--tip left);
top: anchor(--tip bottom);
/* anchor-size 管尺寸 */
width: anchor-size(width);
min-height: anchor-size(height);
/* scroll-driven 管交互 */
animation: hide-on-scroll 0.25s ease-out forwards;
animation-timeline: scroll(root);
}
@keyframes hide-on-scroll {
to {
opacity: 0;
transform: scale(0.95);
pointer-events: none;
}
}
Chrome 115+ / Edge 115+ 完整支持这两个特性。Safari 还没上,对兼容性敏感的项目记得加 @supports 降级:
@supports (anchor-size: width) and (animation-timeline: scroll()) {
.tooltip {
/* 渐进增强 */
}
}
踩过的坑说一声。
anchor-size() 只能用在 width / height / block-size / inline-size 这些尺寸属性里,不能用在 font-size 或 padding 上。另外 scroll-driven animations 的 animation-timeline: scroll(root) 是全局的,如果页面有多个弹层,滚动时它们会同时消失——需要精细控制的场景还是要靠 :scope 或 container-type 限制作用域。
现在做弹层,直接把 JS 扔掉,anchor-size() + scroll-driven animations 全包了。浏览器支持已经是主流,下手不用犹豫。
评论区
登录后可评论。