一、文字垂直居中
<!--多行文字,仅垂直居中-->
<style>
.aBox {
float: left;
width: 200px;
height: 200px;
margin: 10px;
border: 2px solid;
line-height: 200px;
}
.aChild {
display: inline-block;
vertical-align: middle;
line-height: 22px;
}
</style>
<div class="aBox">
<span class="aChild">测试文字试文字测试文字试文字测试文字试文字测试文字试文字测试文字试文字测试文字试文字</span>
</div>
![]()
<!--多行文字,宽度固定,左右垂直居中-->
<style>
.bBox {
position: relative;
height: 300px;
border: 2px solid;
}
.bChild {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 150px;
margin: auto;
display: table;
text-align: center;
}
</style>
<div class="bBox">
<div class="bChild">测试文字试文字测试文字试文字测试文字试文字测试文字</div>
</div>
![]()
二、水平垂直居中--未知高度box放未知高度child
<style>
html, body {
height: 100%;
}
body {
display: table;
width: 100%;
border: 2px solid;
text-align: center;
}
.cChild {
display: table-cell;
height: 50%;
vertical-align: middle;
}
</style>
<div class="cChild">测试文字</div>
<style>
html, body {
height: 100%;
}
body {
display: table;
width: 100%;
}
.dChild {
display: flex;
height: 100%;
align-items: center;
justify-content: center;
}
</style>
<div class="dChild">测试文字</div>
<style>
.eBox {
position: fixed;
left: -100%;
right: 100%;
top: 0;
bottom: 0;
text-align: center;
font-size: 0;
}
.eBox:after {
content: '';
display: inline-block;
vertical-align: middle;
height: 100%;
}
.eBox .eChild {
display: inline-block;
vertical-align: middle;
position: relative;
right: -100%;
}
.eBox .eChild img {
float: left;
}
</style>
<div class="eBox">
<div class="eChild">测试文字</div>
</div>
三、水平垂直居中--未知高度box放已知高度child
<style>
.gChild {
position: absolute;
left: 50%;
top: 50%;
width: 200px;
height: 100px;
background-color: #00f;
margin: -50px 0 0 -100px;
}
</style>
<div class="gChild"></div>
<style>
.hChild {
position: absolute;
width: 200px;
height: 100px;
background-color: #00f;
left:0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
</style>
<div class="hChild"></div>
<style>
.fChild {
position: absolute;
left: 50%;
top: 50%;
width: 200px;
height: 100px;
background-color: #00f;
transform: translate(-50%,-50%);
}
</style>
<div class="fChild"></div>