@container queries无法修改grid-template-columns值的问题求助
问题原因与解决方案
你的代码不生效的核心问题是容器查询的使用逻辑错误:你把container-type: inline-size定义在了.list元素本身,同时又试图在@container规则里修改.list的样式。容器查询的设计是基于祖先容器的尺寸变化来调整后代元素的样式,而非让元素自身查询自身尺寸。
正确的容器查询写法
给.list添加一个父容器,将容器类型定义在这个父容器上,这样@container就能基于父容器的宽度触发样式变化:
/* 新增父容器的样式 */ .list-container { container-type: inline-size; } .list { background-color: grey; display: grid; grid-gap: 4px; grid-template-columns: repeat(5, 1fr); } .letter { display: grid; grid-auto-flow: row; justify-items: center; align-content: center; color: white; padding: 1rem; /* 增加内边距便于观察效果 */ } @container (max-width: 500px) { .list { grid-template-columns: repeat(2, 1fr); } .letter { background-color: green; } }
<div class="list-container"> <div class="list"> <div class="letter">A</div> <div class="letter">B</div> <div class="letter">C</div> <div class="letter">D</div> <div class="letter">E</div> </div> </div>
替代方案:媒体查询(若需求基于视口宽度)
如果你的需求本来就是当浏览器视口宽度小于500px时修改布局,直接用媒体查询更简单,无需容器查询:
.list { background-color: grey; display: grid; grid-gap: 4px; grid-template-columns: repeat(5, 1fr); } .letter { display: grid; grid-auto-flow: row; justify-items: center; align-content: center; color: white; padding: 1rem; } @media (max-width: 500px) { .list { grid-template-columns: repeat(2, 1fr); } .letter { background-color: green; } }
<div class="list"> <div class="letter">A</div> <div class="letter">B</div> <div class="letter">C</div> <div class="letter">D</div> <div class="letter">E</div> </div>
内容的提问来源于stack exchange,提问作者xkeshav
相关产品推荐
相关产品推荐

