垂直居中
.parent > .child
.parent 定高
.child 高度不确定,垂直居中
要点1
不要让 .parent 定高!
使用 padding 和 line-height 即可!
要点2
如果你 .parent 不得不定高(如全屏高度)
你有如下方法:
-
table
.parent display: table;
.child display: table-cell;vertical-align: middle; -
100% inline block
.parent:before{
content:'';
display: inline-block;
height: 100%;
vertical-align: middle;
}
.parent:after{
content:'';
display: inline-block;
height: 100%;
vertical-align: middle;
} -
div 装 tble
一级框:display: table;
二级框:display: table-row;
三级框:display: table-cell;
四级元素垂直居中 -
margin-top -50%
width: 300px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -150px;
height: 100px;
margin-top: -50px;
绝对定位加-margin法,child定高宽 -
translate -50%
.parent{
height: 600px;
position: relative;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
CSS3 translate -50%法 -
absolute margin auto
.parent{
height: 600px;
border: 1px solid red;
position: relative;
}
.child{
border: 1px solid green;
position: absolute;
width: 300px;
height: 200px;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
绝对定位四边0px,child定高宽 -
flex
.parent{
height: 600px;
display: flex;
justify-content: center;//水平居中
align-items: center;//垂直居中
}
.child{
width: 300px;//子元素定宽
}
CSS3 flex布局法