垂直和水平居中,无需担心高度或宽度
以下技术允许你将内容添加到 HTML 元素并将其水平和垂直居中,而不必担心其高度或宽度。
外容器
- 应该有
display: table;
内部容器
- 应该有
display: table-cell;
- 应该有
vertical-align: middle;
- 应该有
text-align: center;
内容框
- 应该有
display: inline-block;
- 应重新调整水平文本对齐,例如。
text-align: left;
或text-align: right;
,除非你希望文本居中
演示
HTML
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
You can put anything here!
</div>
</div>
</div>
CSS
body {
margin : 0;
}
.outer-container {
position : absolute;
display: table;
width: 100%; /* This could be ANY width */
height: 100%; /* This could be ANY height */
background: #ccc;
}
.inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
text-align: left;
background: #fff;
padding: 20px;
border: 1px solid #000;
}
另见这个小提琴 !