使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; /* full viewport height for vertical centering */ } .centered-div { display: inline-block; vertical-align: middle; line-height: normal; }
<div class="container"> <div class="centered-div">centered content</div> </div>