讓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中文網其他相關文章!