網頁元素置中攻略記_(1)元素水平置中,置中攻略
行內元素水平置中方案
- 行內元素包裹在一個屬性display為block的父層元素中,父塊
text-align:center即可實現
代碼實現
index.html
<!DOCTYPE html><html lang="zh"> <head> <meta charset="UTF-8"> <title>行內元素水平置中</title> <style type="text/css"> p { display: ineline-block; } .testDiv { text-align: center; width: 500px; height: 500px; background: rgb(78, 243, 145); } /* 適用元素:文字,連結,及其其它inline或者inline-*類型元素(inline-block,inline-table,inline-flex) */ </style> </head> <body> <div class="testDiv"> <span>我是測試文本</span> <b>|我也是</b> <p>我也是測試的啊</p> </div> </body></html>
一個塊狀元素水平置中方案
設定塊的margin為左右為auto即可,上下margin可以根據需求設定{margin:0 auto}
代碼實現
index.html
<!DOCTYPE html><html lang="zh"> <head> <meta charset="UTF-8"> <title>一個塊元素水平置中</title> <style type="text/css"> #container { width: 800px; height: 800px; background: rgb(129, 97, 53); margin: 0 auto; } </style> </head> <body> <div id="container"> </div> </body></html>
多個塊狀元素水平置中方案
- 參考第一個實現,內部DIV設定為內聯塊,包裹塊設定
text-align:center
代碼實現
index.html
<!DOCTYPE html><html lang="zh"> <head> <meta charset="UTF-8"> <title>多個塊元素水平置中</title> <style type="text/css"> #container { text-align: center; background: rgb(26, 188, 130); width: 500px; height: 500px; } #testDiv1 { display: inline-block; width: 100px; height: 100px; background: #03232A; } #testDiv2 { display: inline-block; width: 100px; height: 100px; background: #122A03; } #testDiv3 { display: inline-block; width: 100px; height: 100px; background: #189FBD; } #testDiv4 { display: inline-block; width: 100px; height: 100px; background: #E20FAD; } </style> </head> <body> <div id="container"> <div id="testDiv1"></div> <div id="testDiv2"></div> <div id="testDiv3"></div> <div id="testDiv4"></div> </div> </body></html>