absolute元素水平居中


原始(未居中):

 1 .con{
 2   width:200px;
 3   height:200px;
 4   background:#ccc;
 5   position:relative;
 6 }
 7 .abs{
 8   width:40px;
 9   height:20px;
10   background:steelblue;
11   position:absolute;
12   bottom:0;
13 }
 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4   <meta charset="utf-8">
 5   <meta name="viewport" content="width=device-width">
 6   <title>JS Bin</title>
 7 </head>
 8 <body>
 9 <div class="con">
10   <div class="abs"></div>
11 </div>
12 </body>
13 </html>

Solution 1:

給absolute元素的left設為50%, margin-left設為absolute元素寬度一半的負數

 1 .con{
 2   width:200px;
 3   height:200px;
 4   background:#ccc;
 5   position:relative;
 6 }
 7 .abs{
 8   width:40px;
 9   height:20px;
10   background:steelblue;
11   position:absolute;
12   bottom:0;
13 
14   left:50%;
15   margin-left:-20px;
16 }

Solution 2:

原理和1相似,設left:50%,但使用css3的transform:translate(x,y);

 1 .con{
 2   width:200px;
 3   height:200px;
 4   background:#ccc;
 5   position:relative;
 6 }
 7 .abs{
 8   width:40px;
 9   height:20px;
10   background:steelblue;
11   position:absolute;
12   bottom:0;
13   
14   left:50%;
15   transform:translate(-50%);
16 }

Solution 3:

margin:auto;實現居中,但是absolute元素一定要有寬度,並且如果寬度不合適(常見於ul li)也是不會居中的

 1 .con{
 2   width:200px;
 3   height:200px;
 4   background:#ccc;
 5   position:relative;
 6 }
 7 .abs{
 8   width:40px;
 9   height:20px;
10   background:steelblue;
11   position:absolute;
12   bottom:0;
13   left:0;
14   right:0;
15   margin:0 auto;
16 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM