1、绝对定位(left/top为50%) + 负margin-left/top(值为自身宽高的一半)
div{
position: absolute;
width: 100px;
height: 100px;
margin-left: -50px;
margin-top: -50px;
left: 50%;
top: 50%;
}
2、绝对定位(上右下左都设为0)+ margin:0 auto【ie7以前不支持】
div{
position: absolute;
margin: 0 auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
3、绝对定位(left和top为50%) + CSS3平移自身宽高的一半translate(-50%, -50%)【ie8以前不支持】
div{
position: absolute;
transform: translate(-50%, -50%);
left: 50%;
top: 50%;
}
4、利用弹性布局。父级CSS设为display:flex + justify-content:center + align-items:center
div{
display: flex;
justify-content: center;
align-items: center;
}
5、表格布局:text-align:center + vertical-align:middle
div{
display: table;
text-align: center;
vertical-align: middle;
}
方法一推荐使用,注意div需要已知宽高;
方法二ie7以前不支持,因为margin:0 auto不好使,处理方法是利用css的hack兼容写法,让margin为负值,值是容器自身宽度的一半即可;
方法三ie8以前不友好,css3兼容性的问题;
方法四是flex布局只支持高版本浏览器;
方法五不太好,设置为表格布局后会引起一系列变化。