在 90vw/50vh 边界内二维扩展正方形 Flexbox 网格
建议先按当前行列数算出统一的 cell 边长,再把这个尺寸同时用在父容器和 item 上,不要让 .item 靠 flex:1 和 aspect-ratio 自己撑。计算公式是 cell = min(90vw / COL, 50vh / ROW)。然后令 parent 的宽高分别为 cell * COL 和 cell * ROW,每个 item 固定为 cell × cell,并加上 box-sizing: border-box。增删 item 或窗口 resize 后重新算一次,就不会只剩一行、其余行溢出。
为什么会溢出
原来的布局里,.row 和 .item 都用了 flex: 1 1 0。行内 item 先按父容器宽度分到宽度,接着 aspect-ratio: 1/1 把高度设成与宽度相同。多行时,这个高度再加上 border 就会把 #parent 撑出 max-height: 50vh。max-height 只是上限,不会反过来压缩已经由宽度算出的 aspect-ratio 高度。另外,默认 box-sizing 是 content-box,border: 10px 还会额外增加尺寸。改成 display: grid 但 item 仍靠 aspect-ratio 和 1fr 时,约束方式差不多,所以结果看起来一样。
推荐做法:用 JS 计算统一 cell 尺寸
生成结构时,row 用 div 更标准,不建议用 document.createElement('row')。网格数量或窗口尺寸变化后调用 fitGrid():
const ROW = 3;
const COL = 4;
const parent = document.getElementById('parent');
for (let y = 0; y < ROW; y++) {
const row = document.createElement('div');
row.className = 'row';
for (let x = 0; x < COL; x++) {
const item = document.createElement('div');
item.className = 'item';
row.appendChild(item);
}
parent.appendChild(row);
}
function fitGrid() {
const maxW = window.innerWidth * 0.9;
const maxH = window.innerHeight * 0.5;
const cell = Math.floor(Math.min(maxW / COL, maxH / ROW));
parent.style.width = `${cell * COL}px`;
parent.style.height = `${cell * ROW}px`;
parent.style.setProperty('--cell-size', `${cell}px`);
}
fitGrid();
window.addEventListener('resize', fitGrid);
对应 CSS:
body {
background-color: grey;
}
#parent {
background-color: white;
display: flex;
flex-direction: column;
max-width: 90vw;
max-height: 50vh;
}
.row {
display: flex;
}
.item {
width: var(--cell-size);
height: var(--cell-size);
flex: 0 0 auto;
box-sizing: border-box;
border: solid black 10px;
}
这里的 Math.floor 用来避免小数像素让总宽高略微超过上限。行列数会动态变化时,把 ROW、COL 换成当前数量,再调用 fitGrid()。如果父容器有 padding,或者 item 之间有 gap,要先把这些额外空间从 maxW/maxH 里扣掉,再算 cell。
CSS Grid 的替代写法
如果行列数能通过 CSS 变量提供,也可以用 Grid,让父容器自己满足宽高比:
#parent {
--cols: 4;
--rows: 3;
width: min(90vw, calc(50vh * var(--cols) / var(--rows)));
aspect-ratio: var(--cols) / var(--rows);
max-width: 90vw;
max-height: 50vh;
display: grid;
grid-template-columns: repeat(var(--cols), 1fr);
grid-template-rows: repeat(var(--rows), 1fr);
}
.item {
box-sizing: border-box;
border: solid black 10px;
}
这个写法靠父容器的宽高比和等分轨道得到正方形格子,不要再给 item 加会反过来撑高的 flex 尺寸。动态增删 item 时,同步更新 --cols、--rows 即可。
注意事项
- 给 item 加
box-sizing: border-box,让 border 算进正方形尺寸。 - 不要让
.row和.item同时靠flex:1决定二维尺寸;二维约束要么用 JS 算统一 cell,要么用父容器宽高比加 Grid。 - 有 gap 时公式改为:
cell = min((maxW - (COL-1)*gap) / COL, (maxH - (ROW-1)*gap) / ROW),父容器尺寸还要加上 gap 占用的总空间。 - 每次窗口
resize或网格数量变化后重新布局,才能保持填满且不超过90vw/50vh。
备注:内容仅供参考。
