CSS锚点定位Polyfill无法处理position-try回退问题
解决Oddbird CSS锚点定位Polyfill中position-try回退规则不生效的问题
核心问题排查与修复步骤
1. 手动传入position-try规则到Polyfill配置
当前Polyfill默认不会自动解析CSS中的@position-try规则,需要在初始化时通过positionTries参数显式传入回退定义:
修改index.js中的Polyfill初始化代码:
// index.js import polyfill from "@oddbird/css-anchor-positioning/fn"; window.addEventListener("DOMContentLoaded", () => { if (!("anchorName" in document.documentElement.style)) { polyfill({ elements: [ document.getElementById("exampleA"), document.getElementById("exampleAChild"), document.getElementById("exampleB"), document.getElementById("exampleBChild") ], // 手动添加position-try规则 positionTries: { '--anchor-fallback': { top: 'anchor(bottom)', right: 'anchor(right)', left: 'revert' } } }); } });
2. 确保触发回退的条件成立
position-try只有在初始定位的元素溢出视口/容器时才会触发回退逻辑。当前示例可能未满足溢出条件,导致回退规则未执行。调整布局让初始位置触发溢出:
修改CSS中的#anchors样式:
#anchors { display: flex; justify-content: space-between; padding: 0 20px; margin-top: 50px; }
这样Example B会被放置在页面右侧,其子元素初始left: anchor(left)会超出视口宽度,触发回退规则切换为右对齐。
3. 验证Polyfill版本
确保使用的是最新版本的@oddbird/css-anchor-positioning,旧版本可能对position-try的支持存在缺陷。执行更新命令:
npm update @oddbird/css-anchor-positioning
验证修复效果
完成上述修改后刷新页面:
Example A的子元素保持初始左对齐(无溢出)Example B的子元素触发回退规则,切换为right: anchor(right)的对齐方式(初始左对齐溢出视口)
内容的提问来源于stack exchange,提问作者TheLovelySausage
相关产品推荐
相关产品推荐

