使div居中是最不可能的事情
Flexbox 是一种垂直和水平居中内容的现代方式:
.container { display: flex; justify-content: center; align-items: center; height: 100vh; }
<div class="container"> <div class="centered-div">Centered Content</div> </div>
CSS Grid 还可以居中内容:
.container { display: grid; place-items: center; height: 100vh; }
<div class="container"> <div class="centered-div">Centered Content</div> </div>
您可以使用绝对定位将 div 居中:
.container { position: relative; height: 100vh; } .centered-div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
<div class="container"> <div class="centered-div">Centered Content</div> </div>
对于简单的水平居中,请使用 margin: auto:
.centered-div { width: 50%; margin: 0 auto; }
<div class="centered-div">Centered Content</div>
对于内联或内联块元素:
.container { text-align: center; line-height: 100vh; } .centered-div { display: inline-block; vertical-align: middle; line-height: normal; }
<div class="container"> <div class="centered-div">Centered Content</div> </div>
以上是如何让div居中?的详细内容。更多信息请关注PHP中文网其他相关文章!