1.relative+margin-top
注意:父元素 必须是有width和height属性
.parent {
width: 500px;
height: 500px;
}
.container {
width: 100px;
height: 100px;
margin: 0 auto; /*水平居中*/
position: relative;
top: 50%; /*偏下移动*/
margin-top: -50px; /*减去盒子本身的一半高度*/
}
2.relative+transform
注意:父元素 必须是有width和height属性
.parent {
width: 500px;
height: 500px;
}
.container {
width: 100px;
height: 100px;
margin: 0 auto; /*水平居中*/
position: relative;
top: 50%; /*偏下移动*/
transform: translateY(-50%); /*让盒子沿着Y向上移动盒子高度的50%*/
}
3.flex
.parent {
width: 500px;
height: 500px;
display: flex;
align-items: center; /*定义body的元素垂直居中*/
justify-content: center; /*定义body的里的元素水平居中*/
}
.container {
width: 100px;
height: 100px;
}
4.table+table-cell
.parent {
width: 500px;
height: 500px;
display: table
}
.container {
width: 100px;
height: 100px;
display: table-cell;
vertical-align: middle;
text-align: center;
}
5.relative+absolute
.parent{
width: 500px;
height: 500px;
position: relative;
}
.container{
width: 100px;
height: 100px;
position: absolute;
top:50%;
left:50%;
margin-left:-50px;
margin-top:-50px;
text-align: center;
}
.parent {
width: 500px;
height: 500px;
position: relative;
}
.container {
width: 100px;
height: 100px;
overflow: auto;
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}