Bootstrap Grid:创建等间距居中正方形瓦片布局需求
Bootstrap 正方形瓦片网格布局解决方案
Got it!我来帮你实现这个满足所有要求的瓦片网格布局,直接上干货:
核心实现要点
要达成你要的效果,需要解决三个关键问题,我一一拆解:
- 正方形瓦片:用
padding-bottom: 100%的技巧让容器高度等于宽度,再通过绝对定位让内容填满整个正方形区域 - 统一间距:利用Bootstrap Grid的
g-*和gy-*类,让水平、垂直间距在所有屏幕尺寸下保持一致 - 整体居中:结合
container的自动左右边距和行的justify-content-center,确保网格始终在屏幕中央,左右留白对称
完整代码示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Bootstrap Square Tiles Grid</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> <style> body { background: #a5b5c5; padding: 2rem 0; /* 给页面上下加一点内边距,避免瓦片贴顶/贴底 */ } /* 正方形瓦片容器核心样式 */ .tile-wrap { position: relative; padding-bottom: 100%; /* 高度等于宽度,实现正方形 */ overflow: hidden; } /* 瓦片内部内容容器 */ .tile-content { position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; background: #fff; border-radius: 8px; /* 可选:给瓦片加圆角,增强视觉效果 */ box-shadow: 0 2px 8px rgba(0,0,0,0.1); /* 可选:添加阴影提升层次感 */ } </style> </head> <body> <!-- 容器确保整体居中,左右留白对称 --> <div class="container"> <!-- g-4设置水平间距,gy-4设置垂直间距,justify-content-center让列居中排列 --> <div class="row g-4 gy-4 justify-content-center"> <!-- 响应式列:不同屏幕下每行显示不同数量的瓦片 --> <div class="col-12 col-sm-6 col-md-4 col-lg-3"> <div class="tile-wrap"> <div class="tile-content">Tile 1</div> </div> </div> <div class="col-12 col-sm-6 col-md-4 col-lg-3"> <div class="tile-wrap"> <div class="tile-content">Tile 2</div> </div> </div> <div class="col-12 col-sm-6 col-md-4 col-lg-3"> <div class="tile-wrap"> <div class="tile-content">Tile 3</div> </div> </div> <div class="col-12 col-sm-6 col-md-4 col-lg-3"> <div class="tile-wrap"> <div class="tile-content">Tile 4</div> </div> </div> <div class="col-12 col-sm-6 col-md-4 col-lg-3"> <div class="tile-wrap"> <div class="tile-content">Tile 5</div> </div> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> </body> </html>
代码细节说明
- 间距控制:
g-4和gy-4是Bootstrap的间距类,g-4设置水平方向的 gutter(列之间的间距),gy-4设置垂直方向的行间距,两者数值一致,确保所有方向间距统一 - 响应式布局:
col-12 col-sm-6 col-md-4 col-lg-3表示:- 移动端(<576px):每行1个瓦片
- 平板(≥576px):每行2个瓦片
- 中等屏幕(≥768px):每行3个瓦片
- 大屏(≥992px):每行4个瓦片
- 正方形瓦片:
tile-wrap的padding-bottom: 100%让容器高度等于自身宽度,tile-content用绝对定位填满整个容器,保证不管内容多少,瓦片始终是正方形 - 居中效果:
container自带左右margin: auto,配合行的justify-content-center,让整个网格在屏幕中水平居中,左右边缘到最外侧瓦片的距离完全相等
内容的提问来源于stack exchange,提问作者RoyalRagger
相关产品推荐
相关产品推荐

