如何使用Flexbox实现所有区块等宽等高的4x4网格布局
调整后的Flexbox等尺寸网格实现
完整代码
CSS
/* 补全高度参照,否则容器的100%高度不生效 */ html, body { height: 100%; margin: 0; } .grid-container { min-height: 100%; display: flex; flex-wrap: wrap; /* 替换子项margin的更优方案:统一控制间距,无叠加问题 */ gap: 20px; padding: 20px; box-sizing: border-box; } .grid-container > div { /* 4列的基准宽度:减去gap和容器padding的分摊尺寸 */ flex: 0 0 calc(25% - 25px); display: flex; justify-content: center; align-items: center; /* 核心:强制宽高一致,所有区块尺寸完全统一 */ aspect-ratio: 1 / 1; } .box1{background-color:red;} .box2{background-color:orange;} .box3{background-color:purple;} .box4{background-color:grey;} .box5{background-color:blue;} .box6{background-color:green;} .box7{background-color:pink;} .box8{background-color:lightgrey;} .box9{background-color:yellow;} .box10{background-color:cyan;} .box11{background-color:brown;} .box12{background-color:maroon;} .box13{background-color:navy;} .box14{background-color:lime;} .box15{background-color:teal;} .box16{background-color:silver;}
HTML
<div class="grid-container"> <div class="box1">Test 1</div> <div class="box2">Test 2</div> <div class="box3">Test 3</div> <div class="box4">Test 4</div> <div class="box5">Test 5</div> <div class="box6">Test 6</div> <div class="box7">Test 7</div> <div class="box8">Test 8</div> <div class="box9">Test 9</div> <div class="box10">Test 10</div> <div class="box11">Test 11</div> <div class="box12">Test 12</div> <div class="box13">Test 13</div> <div class="box14">Test 14</div> <div class="box15">Test 15</div> <div class="box16">Test 16</div> </div>
改动点说明
- 删掉了原代码中无效的嵌套样式
.grid2x2 > div > div,对应HTML里没有这层嵌套 - 原容器类名
grid2x2改为grid-container,更具通用性,适配不同列数的网格场景 - 补全了
html/body的高度设置,否则容器的min-height:100%没有参照,无法正常撑满 - 用容器的
gap属性替代子项的margin:20px,避免相邻子项边距叠加,间距更均匀 - 新增
aspect-ratio: 1/1强制所有子项宽高一致,不受内容多少影响 - 子项的
flex设置为0 0 calc(25% - 25px),对应4列的宽度拆分;要改成2x2网格的话,把参数调整为0 0 calc(50% - 30px)即可 - 加了
align-items: center让区块内的内容垂直居中,避免文字顶在顶部
如果需要兼容不支持
aspect-ratio的老旧浏览器,可以给子项加固定高度规则:比如容器高度固定为100vh时,子项加height: calc(25vh - 30px)(对应4行的高度拆分,根据实际边距调整数值即可)
内容的提问来源于stack exchange,提问作者user779681
相关产品推荐
相关产品推荐

