Chrome 109中@container查询不生效,疑使用方式有误求解答
问题原因与修正方案
你的代码问题出在容器查询的作用范围限制:容器查询(@container)只能修改容器元素的后代元素样式,而你当前将container-type: inline-size定义在.col2上,却试图在@container规则中修改它的父元素.grid的样式,这不符合容器查询的工作逻辑,因此不会生效。
Chrome 109确实原生支持容器查询(该特性从Chrome 105起就已支持),所以问题并非浏览器兼容性导致,而是使用方式有误。
修正方案1:将容器设为.grid(匹配你修改.grid样式的需求)
如果你的目标是当.grid宽度小于150px时改变它的背景色,只需把container-type: inline-size移到.grid上即可:
.grid { display: grid; grid-template-columns: 1fr 2fr; resize: horizontal; overflow: hidden; container-type: inline-size; /* 移到这里 */ } .col1 { background-color: #ccc; height: 150px; } .col2 { background-color: #eee; height: 150px; } @container (max-width: 150px) { .grid { background-color: red; } }
修正方案2:针对.col2的后代元素设置样式(容器查询常规用法)
如果你的目标是当.col2宽度小于150px时修改它内部元素的样式,可调整选择器为.col2的后代:
.grid { display: grid; grid-template-columns: 1fr 2fr; resize: horizontal; overflow: hidden; } .col1 { background-color: #ccc; height: 150px; } .col2 { background-color: #eee; height: 150px; container-type: inline-size; } @container (max-width: 150px) { .col2::after { /* 示例:修改.col2的伪元素样式 */ content: "宽度小于150px"; color: red; } }
内容的提问来源于stack exchange,提问作者Oscar
相关产品推荐
相关产品推荐

