popover 跟随触发按钮:以前只能靠 JS 监听 resize/scroll 实时算位置。CSS 锚点定位写 position: anchor(anchor-name ...),元素就像挂在锚点上一样,锚点移动它自动跟着,甚至能用 position-try 自动翻转,空间不够时换到另一侧。
这是 2024 后浏览器才原生支持的能力(Chrome 率先),配合 popover 属性几乎可以零 JS 做菜单、提示条、下拉组合。配合 @position-try 规则可声明多套兜底位置。
<style> .btn { anchor-name: --menu; } .pop { position: absolute; position-anchor: --menu; top: anchor(bottom); left: anchor(left); position-try: flip-block; } </style> <button class="btn" popovertarget="p">打开菜单</button> <div class="pop" id="p" popover>菜单自动吸附在按钮下方</div>