Bootstrap5如何实现左侧6列标准布局、右侧自适应占满浏览器剩余宽度
Bootstrap 5 实现左栏对齐标准栅格、右栏贴边布局的方案
你需要的这种布局可以通过少量自定义类结合Bootstrap 5原生工具类实现,核心是保证左侧内容和全站标准container的边距对齐,右侧自动撑满剩余窗口宽度,不会出现左侧内容贴浏览器边缘的问题。
可用代码示例
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <style> /* 仅需增加这一段自定义样式,完全匹配Bootstrap原生container的断点规则 */ .container-half-left { padding-left: calc(50vw - 50%); } @media (min-width: 576px) { .container-half-left { padding-left: calc(50vw - 270px); } } @media (min-width: 768px) { .container-half-left { padding-left: calc(50vw - 360px); } } @media (min-width: 992px) { .container-half-left { padding-left: calc(50vw - 480px); } } @media (min-width: 1200px) { .container-half-left { padding-left: calc(50vw - 570px); } } @media (min-width: 1400px) { .container-half-left { padding-left: calc(50vw - 660px); } } .bg-blue { background: #0d6efd; } .white { color: #fff; } </style> </head> <body> <div class="hero-interior-banner bg-blue"> <!-- 去掉container-fluid,直接用无间距行 --> <div class="row g-0 align-items-stretch"> <!-- 左侧栏加自定义类,对齐标准container左半部分 --> <div class="col-12 col-xl-6 container-half-left px-5 pt-5 pb-3 text-center text-xl-start"> <h1 class="text-uppercase white">Title</h1> <p class="white">Some text would go here</p> <p> <a href="#" class="button-white">Learn more</a></p> </div> <!-- 右侧栏自动撑满剩余宽度,贴右边缘 --> <div class="col flex-grow-1 px-0"> <div class="d-none d-xl-block hero-interior-banner-image h-100"> <img class="interior-hero-overlay h-100" src="https://via.placeholder.com/400" alt="Hero overlay" /> <img class="img-fluid h-100 w-100 object-fit-cover" src="https://via.placeholder.com/400" alt="Cancer research" /> </div> </div> </div> </div> </body> </html>
实现逻辑说明
- 自定义的
container-half-left类完全遵循Bootstrap原生container的断点尺寸规则,左侧内边距和标准容器的左侧边距完全对齐,保证你的左侧6列内容和全站其他标准栅格内容在同一竖直线上,不会贴浏览器左边缘 - 右侧栏使用Bootstrap自带的
flex-grow-1工具类,自动占满行内剩余宽度,始终紧贴浏览器右边缘 - 不需要修改Bootstrap原生源码,也不会影响全站其他栅格规则,适配所有Bootstrap预设的响应式断点
内容的提问来源于stack exchange,提问作者Aaron Blomberg
相关产品推荐
相关产品推荐

