absolute元素水平居中
生活随笔
收集整理的這篇文章主要介紹了
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 }?
轉載于:https://www.cnblogs.com/coding-swallow/p/7792704.html
新人創作打卡挑戰賽發博客就能抽獎!定制產品紅包拿不停!總結
以上是生活随笔為你收集整理的absolute元素水平居中的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 玄学小记.5 ~ Bluestein's
- 下一篇: CSU-1975 机器人搬重物(BFS)