如何实现网格子元素在240px-250px间自适应收缩?
实现网格子元素在240px-250px间自适应收缩
你当前的写法中,minmax(240px, 250px)配合auto-fit会让网格优先以250px宽度排列子元素,只有当容器完全放不下整列时才会换行,不会主动触发子元素的收缩。要实现默认250px、收缩下限240px的效果,可以通过以下方式调整:
- 父容器的网格列定义改为
repeat(auto-fit, minmax(240px, 1fr)),让列的最小宽度锁定240px,最大可占满当前可用空间 - 给每个子元素添加
max-width: 250px; width: 100%;,限制子元素的最大宽度为250px,同时让它自适应父列的宽度
修改后的代码如下:
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); column-gap: 16px; background: blue"> <div style="background: red; height: 326px; margin-bottom: 36px; max-width: 250px; width: 100%;"> <p> </p> </div> <div style="background: red; height: 326px; margin-bottom: 36px; max-width: 250px; width: 100%;"> <p> </p> </div> <div style="background: red; height: 326px; margin-bottom: 36px; max-width: 250px; width: 100%;"> <p> </p> </div> <div style="background: red; height: 326px; margin-bottom: 36px; max-width: 250px; width: 100%;"> <p> </p> </div> </div>
这样调整后,当父容器宽度足够时,子元素会保持250px的宽度;当父容器收缩,子元素会从250px逐步缩小到240px,此时网格会自动换行,确保所有子元素不会小于240px。
内容的提问来源于stack exchange,提问作者Sarahdactyl
相关产品推荐
相关产品推荐

