css3 - css垂直水平居中?
問題描述
如何實現B在A中,垂直和水平方向都居中?代碼如下:
<!DOCTYPE html><html lang='zh'><head> <meta http-equiv='X-UA-Compatible' content='IE=Edge'> <meta charset='UTF-8'/> <title></title> <style>#A { position: relative; width: 500px; height: 500px; background-color: green;}#B { position: absolute; max-width: 300px; max-height: 300px; background-color: blue;} </style></head><body><p id='A'> <p id='B'>哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥給哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥給哥哥哥哥哥哥哥給哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥給哥哥哥哥哥哥哥給哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥給哥哥哥哥哥哥哥給哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥給哥哥哥 </p></p></body></html>
問題解答
回答1:兩種方法:
第一種:
#A { position: relative; width: 500px; height: 500px; background-color: green;}#B { position: absolute; max-width: 300px; max-height: 300px; background-color: blue; /* add */ margin:auto; left:0; right:0; top:0; bottom:0;}
第二種:
#A { position: relative; width: 500px; height: 500px; background-color: green;}#B { position: absolute; max-width: 300px; max-height: 300px; background-color: blue; /* add */ top:50%; left:50%; transform:translate(-50%,-50%);}回答2:
#A {display:table-cell;vertical-align:middle; } #B {/* position:absolute; */margin:0 auto; }
http://jsfiddle.net/7uakz7p1/
回答3:今天剛學到的一種比較簡單的方法:父容器設置display: flex; 要居中的子元素設置margin: auto;即可。本例中
#A {position: relative;width: 500px;height: 500px;background-color: green;/*add*/display: flex;display: -webkit-flex; }#B {/*position: absolute;*/max-width: 300px;max-height: 300px;background-color: blue;/*add*/margin: auto; }
ps. IE下好像有問題...
回答4:#A { position: relative; width: 500px; height: 500px; background-color: green;}#B { width: 50%; height: 50%; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; max-width: 300px; max-height: 300px; background-color: blue;} 回答5:
正好發現一個網站,給了好多解決方案 Centering in CSS: A Complete Guide
回答6:http://jsfiddle.net/nbayw7ea/
回答7:http://css-tricks.com/centering-css-complete-guide/
相關文章:
1. Python爬蟲如何爬取span和span中間的內容并分別存入字典里?2. mysql - 把一個表中的數據count更新到另一個表里?3. 請教使用PDO連接MSSQL數據庫插入是亂碼問題?4. python - 爬蟲模擬登錄后,爬取csdn后臺文章列表遇到的問題5. visual-studio - Python OpenCV: 奇怪的自動補全問題6. linux - Ubuntu下編譯Vim8(+python)無數次編譯失敗7. node.js - nodejs開發中常用的連接mysql的庫8. mysql 查詢身份證號字段值有效的數據9. 視頻文件不能播放,怎么辦?10. mysql - 分庫分表、分區、讀寫分離 這些都是用在什么場景下 ,會帶來哪些效率或者其他方面的好處
