(css定位)position:absolute;时居中


我们习惯用margin:0,auto;居中元素,但有时我们必须要让元素获得position:absolute;,这时候,再用margin:0,auto;居中是无效的。

举个例子

 1 <!DOCTYPE html>
 2 
 3 <html>
 4 
 5  <head>
 6 
 7   <title>wheel</title>
 8 
 9   <style type="text/css" >
10 
11    #sample{
12 
13     width: 900px;
14 
15     height: 600px;
16 
17     position: absolute;
18 
19     margin: 0,auto;
20 
21     background: #A5A5A5;
22 
23    }
24 
25   </style>
26 
27  </head>
28 
29  <body id="body">
30 
31   <div id="sample">
32 
33   </div>
34 
35  </body>
36 
37 </html>

在这里,虽然css有margin: 0,auto;,显示效果如下图所示,没有居中

(css定位)position:absolute;时居中

我们需要把代码改为

 1 <!DOCTYPE html>
 2 
 3 <html>
 4 
 5  <head>
 6 
 7   <title>wheel</title>
 8 
 9   <style type="text/css" >
10 
11    #sample{
12 
13     width: 900px;
14 
15     height: 600px;
16 
17     position: absolute;
18 
19     left: 50%;
20 
21     margin-left: -450px;
22 
23     background: #A5A5A5;
24 
25    }
26 
27   </style>
28 
29  </head>
30 
31  <body id="body">
32 
33   <div id="sample">
34 
35   </div>
36 
37  </body>
38 
39 </html>

在这里我们做了两个改动,就是加了

    left: 50%;

    margin-left: -450px;

为什么这么改呢,left是在position属性是absolute或fixed时才有效的, left: 50%;意思距离左边是界面的百分之五十,这是div的左边边界正好在画面的中间线,这是我们再左移图片的一半长度的距离,就可移使图片中间与画面中间重叠

而且在缩放时,仍保持居中。

(css定位)position:absolute;时居中


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM