如何在Bootstrap中让等高行填满页面高度且无滚动
解决Bootstrap 8行等高且占满屏幕高度的问题
你需要让8个Bootstrap row元素高度一致,总高度刚好填满屏幕,且无需滚动就能全部显示。之前用h-100/h-50/h-25这类内置类实现等高时,出现了页面溢出的问题,自定义高度类也没起作用,这里提供两种可行方案:
方案一:利用Bootstrap Flex类快速实现
核心思路是用Flexbox的空间分配特性,让所有行自动平分容器高度,同时消除默认间距避免溢出:
- 给外层容器(
container-fluid)添加d-flex flex-column g-0类:d-flex:将容器设为Flex容器flex-column:让内部元素垂直排列g-0:移除row之间的默认间距(gutter),避免额外高度占用
- 给每个
row添加flex-grow-1类:让所有行平分容器的可用高度,自动实现等高
修改后的完整代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Equal rows</title> <!-- Bootstrap core CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> </head> <body class="text-center"> <div class="container-fluid vh-100 d-flex flex-column g-0"> <div class="row flex-grow-1"> <div class="col-lg" style="background-color: lightcoral;"> <h3 style="color: white">lightcoral</h3> </div> </div> <div class="row flex-grow-1"> <div class="col-lg" style="background-color: indigo;"> <h3 style="color: white">indigo</h3> </div> </div> <div class="row flex-grow-1"> <div class="col-lg" style="background-color: red;"> <h3 style="color: white">red</h3> </div> </div> <div class="row flex-grow-1"> <div class="col-lg" style="background-color: lightseagreen;"> <h3 style="color: white">lightseagreen</h3> </div> </div> <div class="row flex-grow-1"> <div class="col-lg" style="background-color: green;"> <h3 style="color: white">green</h3> </div> </div> <div class="row flex-grow-1"> <div class="col-lg" style="background-color: yellow;"> <h3 style="color: white">yellow</h3> </div> </div> <div class="row flex-grow-1"> <div class="col-lg" style="background-color: purple;"> <h3 style="color: white">purple</h3> </div> </div> <div class="row flex-grow-1"> <div class="col-lg" style="background-color: orange;"> <h3 style="color: white">orange</h3> </div> </div> </div> </body> </html>
方案二:自定义CSS类(精细控制)
如果不想依赖Flex类,也可以自定义高度类,同时清除row的默认margin:
- 在自定义CSS中添加:
.row-1-8 { height: calc(100% / 8); margin: 0 !important; /* 清除row默认margin */ }
- 给容器保留
vh-100,给每个row添加row-1-8类即可
为什么之前的方法失效?
- Bootstrap的
h-*类是基于百分比高度,但row本身带有默认的margin-top/margin-bottom,即使设置每个row高度为12.5%(100/8),加上margin后总高度会超过100vh,导致页面溢出。 - Flex的
flex-grow-1会自动分配容器的剩余空间,同时g-0消除了额外间距,完美解决高度溢出问题。
内容的提问来源于stack exchange,提问作者batman
相关产品推荐
相关产品推荐

