如何限制Flex容器中每行的div数量?
限制布局每行显示数量的简便方法
有两种更简便的方式实现你要的“限制每行最多N个图片盒子”的效果,不用反复手动调整宽度:
方法一:基于现有Flex布局改造
利用flex-basis结合calc直接控制每行最大数量,以每行最多3个为例:
#gallery-box { position: relative; display: flex; flex-flow: row wrap; justify-content: center; gap: 10px; /* 可选,给盒子间添加间距 */ } .box { flex: 0 0 calc(100% / 3 - 10px); /* 10px对应上方的gap值,避免间距导致溢出换行 */ aspect-ratio: 1/1; text-align: center; font-size: 22px; padding-top: 16px; font-family: "Quicksand", sans-serif; background-size: cover; background-repeat: no-repeat; background-position: center; }
flex: 0 0 [宽度]:第一个0禁止盒子放大,第二个0禁止盒子缩小(若需允许缩小可改为1)- 要修改每行数量,只需把
calc(100% / 3)中的3换成目标数字即可
方法二:改用CSS Grid(更直观省心)
Grid布局天生适合控制列数,代码更简洁:
#gallery-box { position: relative; display: grid; grid-template-columns: repeat(auto-fill, minmax(calc(100% / 3), 1fr)); gap: 10px; justify-content: center; } .box { aspect-ratio: 1/1; text-align: center; font-size: 22px; padding-top: 16px; font-family: "Quicksand", sans-serif; background-size: cover; background-repeat: no-repeat; background-position: center; }
repeat(auto-fill, minmax(calc(100% / 3), 1fr)):自动填充列,每列最小宽度为calc(100% / 3)(即每行最多3个),视口不足时自动换行减列- 调整每行数量同样只需修改
3为目标数字即可
内容的提问来源于stack exchange,提问作者Karlton Kemerait
相关产品推荐
相关产品推荐

