如何在 css 中将 div 居中
使div居中是最不可能的事情
1. 使用 flexbox 居中
flexbox 是一种垂直和水平居中内容的现代方式:
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
<div class="container">
<div class="centered-div">centered content</div>
</div>
2. 网格居中
css grid 还可以居中内容:
.container {
display: grid;
place-items: center;
height: 100vh;
}
<div class="container">
<div class="centered-div">centered content</div>
</div>
3. 绝对定位居中
您可以使用绝对定位将 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>
4. 使用 margin auto 居中
对于简单的水平居中,请使用 margin: auto:
.centered-div {
width: 50%;
margin: 0 auto;
}
<div class="centered-div">centered content</div>
5. 使用 margin auto 居中
对于内联或内联块元素:
.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>