margin:auto只能水平居中。
为什么设置了
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
就能够水平和垂直都居中呢?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
#id{
background: papayawhip;
width: 200px;
height: 200px;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
</style>
<body>
<div id="id">
</div>
</body>
</html>
首先,你的清楚一点,它并不是水平居中,他只是将你的元素拉伸罢了.
水平垂直居中你可以了解下
display:table 和 display:table-call; 两者配合可以实现元素的居中效果.
不知道你用的什么浏览器,理论来说应该是在左上角的,因为left比right优先级高,top比bottom高
當
1.尺寸限制(寬高有限制)
2.拉伸(有相反的方向屬性:如同時設定top和bottom,left和right)
3.margin:auto時
就會有絕對定位元素的絕對居中效果
Ps:ie8+支持
因为他左也不是,上也不是,,右也不是,下也不是,只有居中了