1.单行文本使用line-height
<div class="parent">
<div class="child">我是垂直居中文本</div>
</div>
//css
child{
line-height: 100px;
}
2.使用table-cell+vertical-align
<div class="parent">
<div class="child">我是垂直居中文本</div>
</div>
//css
.parent{
display: table-cell;
height: 100px;
vertical-align: middle;
}
3.父元素、子元素高度确定高度确定position+margin
<div class="parent">
<div class="child"></div>
</div>
//css 将margin-top设置为本元素高度的一半
.parent{
position: relative;
width: 200px;
height: 100px;
background: red;
}
.child{
position: absolute;
width: 100%;
height: 30px;
top: 50%;
margin-top: -15px;
background: green;
}
4.父元素、子元素高度不确定
<div class="parent">
<div class="child">我会绝对居中</div>
</div>
//css
.parent{
position: relative;
background: red;
width: 200px;
height: 100px;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: green;
}
5.额外元素+margin,与上两个原理一样;多设置了一个额外元素,使额外元素的height为50%,margin-bottom为center元素的高度的负一半-(height + padding)/2
<div class="parent">
<div class="floater"></div>
<div class="child"></div>
</div>
//css
.parent{
width: 200px;
height: 100px;
background: green;
}
.floater{
height: 50%;
margin-bottom: -25px;
}
.child{
width: 50px;
height: 50px;
background: red;
}
6.使用flex
.parent{
display: flex;
flex-flow: column nowrap;
justify-content: center;
}