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 }