码迷,mamicode.com
首页 > 其他好文 > 详细

absolute元素水平居中

时间:2017-11-06 13:58:37      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:ati   一半   name   使用   osi   居中   ges   html   set   

原始(未居中):

 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 }

技术分享

 

absolute元素水平居中

标签:ati   一半   name   使用   osi   居中   ges   html   set   

原文地址:http://www.cnblogs.com/coding-swallow/p/7792704.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!