如何解决Bootstrap 5网页左右留白及左侧内容丢失问题
问题:Bootstrap 5 栅格列布局出现内容偏移(右侧空白、左侧内容丢失)
我在用Bootstrap 5的栅格列做页面开发,完成后发现屏幕右侧出现空白,左侧部分内容丢失。
原HTML代码:
<div id="skills"> <div id="container"> <div class="row"> <div class="row align-items-center"> <div class="col align-self-center"> <img height="50%" width="50%" src="./images/frontend.png" alt="frontend img"> <h2>Frontend Development</h1> <p>I use simple html, css, and js skills to create your frontend websites, with slight animations.</p> </div> <div class="col align-self-center"> <img height="50%" width="50%" src="./images/full-stack-developer-icon.png" alt="fullstack img"> <h2>Full Stack Development</h2> <p>I use the skills of frontend and backend combined to create your site. Recommened for most users.</p> </div> <div class="col align-self-center"> <img height="50%" width="50%" src="./images/backend.png" alt="backend img"> <h2>Backend development</h2> <p>I use Node.js and express.js to create your backend site. Requires frontend files.</p> </div> </div> </div> </div> </div>
原CSS代码:
#skills p { font-family: "Dancing Script", sans-serif; font-weight: bold; font-size: larger; } #skills h2{ font-family: "Solitreo", sans-serif; }
我尝试设置margin,但没能解决问题。
解决方案
核心原因
你嵌套了多余的.row容器——Bootstrap的.row自带负margin,用来抵消.container的内边距,嵌套row会触发双重负margin,直接导致布局偏移、横向滚动和内容丢失。
修复步骤
- 删除外层多余的
<div class="row">,只保留包裹列的那一个.row - 建议把容器的
id="container"改成class="container",符合Bootstrap官方规范(避免id和原生类名混淆) - 顺便修复原代码里的标签错误:
<h2>用了<h1>闭合,这也可能引发布局异常
修复后的HTML代码
<div id="skills"> <div class="container"> <div class="row align-items-center"> <div class="col align-self-center"> <img height="50%" width="50%" src="./images/frontend.png" alt="frontend img"> <h2>Frontend Development</h2> <p>I use simple html, css, and js skills to create your frontend websites, with slight animations.</p> </div> <div class="col align-self-center"> <img height="50%" width="50%" src="./images/full-stack-developer-icon.png" alt="fullstack img"> <h2>Full Stack Development</h2> <p>I use the skills of frontend and backend combined to create your site. Recommened for most users.</p> </div> <div class="col align-self-center"> <img height="50%" width="50%" src="./images/backend.png" alt="backend img"> <h2>Backend development</h2> <p>I use Node.js and express.js to create your backend site. Requires frontend files.</p> </div> </div> </div> </div>
额外提示
不要手动给.row或.col加margin,Bootstrap栅格系统已经预设了正确的间距逻辑,手动修改会破坏原有布局。
内容的提问来源于stack exchange,提问作者MyMainAccountGotBlocked
相关产品推荐
相关产品推荐

