如何实现Div内元素随窗口大小动态均匀分布?
如何让容器内的等尺寸元素随窗口大小自适应分布并始终填满容器?
我需要实现这样的布局效果:容器内的等尺寸元素,无论窗口大小如何变化,都能在水平和垂直方向均匀分布并填满整个容器。具体需求是:
- 小窗口(移动端):显示为3行2列
- 平板端:切换为2行3列
- 大屏显示器:保持2行3列,仅增大元素间的间距
我之前找到过类似问题,但最佳答案用了jQuery,想问问有没有纯CSS或JSX的更简便实现方式?
下面是我的尝试代码:
HTML 代码
<div class="container-main"> <div class="container"> <div class="box">A</div> <div class="box">B</div> <div class="box">C</div> <div class="box">D</div> <div class="box">E</div> <div class="box">F</div> </div> </div>
CSS 代码
.container-main{ display: flex; background-color: blue; width: 100%; height: 500px; justify-content: space-evenly; } .container{ width: 300px; height: 300px; display: flex; justify-content: space-evenly; flex-wrap: wrap; background-color: red; align-content: space-evenly; } .box{ width: 70px; height: 50px; background-color:#333; padding:20px; border-radius:10px; color:#fff; display:flex; align-items:center; justify-content:center; font-size:40px; font-family:sans-serif; }
目前遇到的问题:
当.container宽度为300px和400px时,元素能均匀分布填满整个容器;但宽度调整为500px和600px时,元素依然保持2行3列,却无法再均匀填满容器空间。
示例效果截图:
- 容器宽度300px:

- 容器宽度400px:

- 容器宽度500px:

- 容器宽度600px:

内容的提问来源于stack exchange,提问作者Nova
相关产品推荐
相关产品推荐

