Bootstrap卡片无法居中求助(新手开发者)
如何用Bootstrap实现卡片在屏幕正中央(垂直+水平居中)
你的代码已经实现了卡片的水平居中,但缺少垂直居中的关键设置——父容器没有占据整个视口高度。以下是修复方案:
核心修改点
要实现屏幕正中央(垂直+水平),需要让承载卡片的父容器(比如body或外层容器)占据整个视口高度,同时启用flex布局来完成双方向居中。
修改后的完整代码
</head> <body class="d-flex align-items-center justify-content-center min-vh-100 m-0"> <div class="container"> <div class="row justify-content-center"> <div class="col-md-4 col-12"> <div class="card bg-card col-12"> <div class="card-body text-center"> <img class="rounded-circle mt-3" src="avatar-jessica.jpeg" alt="Jessica Randall" style="height: 100px; width: auto;"> <div> <h5 class="text-white mt-2">Jessica Randall</h5> <p class="text-green">London, United Kingdom</p> <p class="text-white">"Front-end developer and avid reader."</p> </div> <div class="mx-auto col-9 d-grid gap-3"> <a class="btn btn-primary" href="#" role="button">GitHub</a> <a class="btn btn-primary" href="#" role="button">Frontend Mentor</a> <a class="btn btn-primary" href="#" role="button">LinkedIn</a> <a class="btn btn-primary" href="#" role="button">Twitter</a> <a class="btn btn-primary mb-3" href="#" role="button">Instagram</a> </div> </div> </div> </div> </div> </div> </body>
关键类说明
min-vh-100:让body占据至少100%的视口高度d-flex:将body设置为flex容器align-items-center:在垂直方向上居中内容justify-content-center:在水平方向上居中内容m-0:移除body默认的外边距,避免不必要的滚动条
另一种可选方案(不修改body)
如果不想给body添加类,也可以给外层container设置以下类:
<div class="container d-flex align-items-center justify-content-center min-vh-100">
同时需要给html和body补充基础样式:
html, body { height: 100%; margin: 0; }
内容的提问来源于stack exchange,提问作者SiCa Pfe
相关产品推荐
相关产品推荐

