如何用Bootstrap实现左右等大相邻方块,左侧为2列2行结构
解决方案:用Bootstrap实现等宽并排的图库布局
直接用Bootstrap的栅格系统就能实现你要的效果,不需要额外复杂的flexbox代码,自定义CSS仅做细微调整即可:
完整代码示例
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Bootstrap图库布局</title> <!-- 引入Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> <style> /* 仅做收尾调整的自定义CSS */ .gallery-block { border: 1px solid #ddd; /* 可选:给大方块加边框 */ background-color: #f8f9fa; /* 可选:大方块背景色 */ } .gallery-item { border: 1px solid #ddd; /* 可选:小方块边框 */ background-color: #fff; /* 可选:小方块背景色 */ min-height: 150px; /* 固定小方块最小高度,保证2x2结构整齐 */ } .right-block { display: flex; align-items: center; justify-content: center; } </style> </head> <body> <div class="container mt-4"> <!-- 外层等宽容器 --> <div class="row g-4"> <!-- 左侧2x2方块容器 --> <div class="col-md-6 gallery-block"> <div class="row g-3 p-3"> <div class="col-6 gallery-item"></div> <div class="col-6 gallery-item"></div> <div class="col-6 gallery-item"></div> <div class="col-6 gallery-item"></div> </div> </div> <!-- 右侧等大容器 --> <div class="col-md-6 gallery-block right-block"> <!-- 右侧内容,比如单张图片或其他元素 --> <p>右侧方块内容</p> </div> </div> </div> <!-- 可选:引入Bootstrap JS(如果需要交互组件) --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> </body> </html>
关键说明
- 外层
row g-4控制两个大方块的间距,col-md-6保证中等及以上屏幕上两个方块各占一半宽度,Bootstrap的row默认align-items-stretch,能自动让两个方块等高。 - 左侧内部用
row g-3和四个col-6实现2列2行的网格结构,p-3给内部加内边距,避免小方块贴合大方块边框。 - 自定义CSS仅设置边框、背景色等样式,完全符合“核心用Bootstrap,自定义做收尾”的要求。
- 小屏幕下两个方块会自动堆叠,Bootstrap栅格自带响应式适配,无需额外代码。
内容的提问来源于stack exchange,提问作者Hylkest
相关产品推荐
相关产品推荐

