方法1:display:table-cell(IE8+)
.parent{
display: table-cell;
vertical-align: middle;
}
方法2:flex
.parent{
display: flex;
align-items: center;
}
//或
.parent{
display: flex;
flex-direction: column;
justify-content: center;
}
方法3:flex和margin: auto
.parent{
display: flex;
}
.box{
margin: auto;
}
方法4:定位和translate
.box{
position: absolute;
top: 50%;
transform: translateY(-50%);
}
方法5:绝对(或固定)定位和margin: auto
.box{
position: absolute;
top: 0;
bottom: 0;
margin: auto;
}
- top和bottom设为相等的值
- 得确定内部元素的高度,可以用百分比,比较适合移动端
- 也适用于水平居中
方法6:适用于图片或inline-block
.parent{
height: 300px;
line-height: 300px;
}
.box{
display: inline-block;
vertical-align: middle;
}
img{
vertical-align: middle;
}
方法7:伪元素
.parent:after{
display: inline-block;
content: '';
width: 0;
height: 100%;
vertical-align: middle;
}
.box{
display: inline-block;
vertical-align: middle;
}