如何在HTML Body中居中DIV?Flexbox使用疑问咨询
问题:使用Flexbox居中DIV时,元素出现在屏幕中心而非预期位置
刚开始学习CSS,遇到一个问题,若问题过于浅显还请见谅。我想要在HTML的body标签内居中一个DIV元素,尝试使用Flexbox布局实现,但不知为何该DIV出现在了屏幕中心。
我的代码如下:
<html lang="en"> <body> <style type="text/css"> body { background: #6CB3A9; display: flex; justify-content: center; align-items: center; } .main { width:300px; height:300px; background:white; } </style> <div class="main"> <div class="white-bottom"></div> <div class="red-top"></div> <div class="yellow-center"></div> </div> </body> </html>
解答
你当前的代码里,body同时设置了两个Flexbox核心属性:
justify-content: center:控制水平方向的元素居中align-items: center:控制垂直方向的元素居中
两者结合就会让.main元素同时在水平和垂直方向都居中,也就是屏幕的正中心位置。
场景1:仅需水平居中
如果你的需求只是让DIV在水平方向居中,直接移除align-items: center即可:
<html lang="en"> <body> <style type="text/css"> body { background: #6CB3A9; display: flex; justify-content: center; /* 移除垂直居中属性 */ } .main { width:300px; height:300px; background:white; } </style> <div class="main"> <div class="white-bottom"></div> <div class="red-top"></div> <div class="yellow-center"></div> </div> </body> </html>
场景2:需要全屏垂直居中
如果你的需求确实是要让元素在屏幕垂直居中,建议给body添加min-height: 100vh(占满视口高度),同时移除默认margin避免滚动条:
body { background: #6CB3A9; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; }
内容的提问来源于stack exchange,提问作者saurabh-ar
相关产品推荐
相关产品推荐

