如何使Bootstrap中row元素高度与内嵌div保持一致?
解决Bootstrap Row元素高度异常过高的问题
问题根源
你的代码里有两个关键问题导致row高度异常:
body元素设置了固定height:70px,过小的固定高度打破了正常布局流,导致内部容器高度计算混乱。- Bootstrap的
row默认使用flex布局,align-items属性默认值为stretch,会让所有子列(col)拉伸到和最高子元素一致的高度,空的col-lg-2被过度拉伸后,直接导致row高度异常。
修复步骤
移除body的固定高度限制
删掉body标签里的height:70px样式,让body自适应内容高度,也可根据需求设置min-height:100vh让body占满视口高度:<body style="margin:.2%; padding:3%;">让Row贴合子元素实际高度
给包含内容的row添加Bootstrap的align-items-start类,阻止列被不必要地拉伸,让row高度完全贴合子列的实际内容高度:<div class="row align-items-start">优化ScrollableDiv的高度设置
原height:50%依赖父元素高度上下文,改用视口高度单位vh更稳定,比如设置为height:60vh(占视口高度的60%),可根据需求调整:#scrollablediv { overflow-y: scroll; height: 60vh; }修复语法错误
删除末尾多余的未闭合<div class="row">标签,避免布局错乱。
修复后的完整代码
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <meta name="viewport" content="width=device-width, initial-scale=1"/> <style> /* width */ ::-webkit-scrollbar { width: 5px; } /* Scrollbar background */ ::-webkit-scrollbar-track { background: rgb(244, 244, 244); } /* Scrollbar handle */ ::-webkit-scrollbar-thumb { background: rgba(200, 200, 200, 12); } /* Scrollbar handle on hover */ ::-webkit-scrollbar-thumb:hover { background: rgb(80, 20, 160); } p, ul { font-family:Consolas; padding:1%; font-size:12px } footer { text-align:center; font-size:10px; } #scrollablediv { overflow-y: scroll; height:60vh; } /* Making images black-and-white and colourful when hovered. */ img { -webkit-filter: grayscale(100%); -moz-filter: grayscale(100%); filter: grayscale(100%); transition: all .5s ease; } img:hover { -webkit-filter: grayscale(0%); -moz-filter: grayscale(0%); filter: grayscale(0%); } </style> </head> <body style="margin:.2%; padding:3%;"> <header> <h1 style="font-family:consolas; font-size:18px">Header here!</h1> </header> <hr> <div class="row align-items-start"> <div class="col-lg-2"> </div> <div class="col-lg-10"> <div id="scrollablediv"> <h6>Title1</h6> <p> <b>TL;DR:</b> Some text.. <br><br> <b>TS;WM:</b> Some text.. </p> <h6>Title2</h6> <p> Some text.. </p> <h6>Title3</h6> <ul style="font-family:Consolas; font-size:12px; list-style-position: inside;"> <li> Some text.. </li> <li> </li> <li> Some text.. </li> <li> </li> </ul> <h6>Title4</h6> <p> Some text.. </p> <h6>Title5</h6> <p> Some text.. </p> <h6>Title6</h6> <ul style="font-family:Consolas; font-size:12px; list-style-position: inside;"> <li> Some text.. </li> <li> </li> <li> Some text.. </li> <li> </li> </ul> </div> </div> </div> <div class="row"> <div class="col-lg-12"> <footer>© 2022.</footer> </div> </div> <script src="bootstrap-5.2.2-dist/js/bootstrap.bundle.min.js"></script> </body> </html>
内容的提问来源于stack exchange,提问作者Giorgi Tsiklauri
相关产品推荐
相关产品推荐

