绝对定位方式水平垂直居中

两个div,.parent 和 .child,.child 要相对于.parent水平垂直居中。

第一种方式:

1
2
3
4
5
6
7
8
9
10
11
.parent{
display:relative;
}
.child{
width:200px;
height:300px;
top:50%;
margin-top:-100px;
left:50%;
margin-left:-150px;
}

这种方式兼容性比较好,但是要指定.child得宽高,而且宽高修改之后要修改margin-top或margin-left。

第二种方式:

1
2
3
4
5
6
7
8
9
.parent{
position:relative;
}
.child{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%);
}

这种方式ie9以上可用,不需要制定宽高,或者宽高随意指定,不用修改其他属性。