<div id="box"></div>
1.绝对定位实现居中
#box{
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
margin-top: -50px;
margin-left: -50px;
background-color: red;
}
缺点:必须知道box的宽高,否则无法确定!
2.CSS3的做法
#box{
width: 100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
background-color: red;
}
3.absolute和margin:auto;
#box{
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
width: 100px;
height: 100px;
margin: auto;
background-color: red;
}
参考资料: