(css定位)position:absolute;时居中
1、举个例子
<!DOCTYPE html>
<html>
<head>
<title>wheel</title>
<style type="text/css" >
#sample{
width: 900px;
height: 600px;
position: absolute;
margin: 0,auto;
background: #A5A5A5;
}
</style>
</head>
<body id="body">
<div id="sample">
</div>
</body>
</html>
在这里,虽然css有margin: 0,auto;,显示效果如下图所示,没有居中
2、我们需要把代码改为
<!DOCTYPE html>
<html>
<head>
<title>wheel</title>
<style type="text/css" >
#sample{
width: 900px;
height: 600px;
position: absolute;
left: 50%;
margin-left: -450px;
background: #A5A5A5;
}
</style>
</head>
<body id="body">
<div id="sample">
</div>
</body>
</html>
在这里我们做了两个改动,就是加了
left: 50%;
margin-left: -450px;
为什么这么改呢,left是在position属性是absolute或fixed时才有效的, left: 50%;意思距离左边是界面的百分之五十,这是div的左边边界正好在画面的中间线,这是我们再左移图片的一半长度的距离,就可移使图片中间与画面中间重叠
而且在缩放时,仍保持居中。