網頁元素置中攻略記_(4)用CSS3屬性讓元素水平垂直置中,置中css3
flex實現子塊的完美置中方案
父塊使用display:flex屬性,子塊margin自適應即可實現
代碼
index.html
<!DOCTYPE html><html lang="zh"><head> <meta charset="UTF-8"> <title>塊狀元素垂直置中(已知高度)</title> <style> *{margin: 0;padding: 0;} .parent{ display: flex; height:500px; background: #03A1FA; } .child{ width: 100px; height: 100px; margin: auto; background: #BB3713; } /* 這個依賴於設定`margin`值為`auto`值,自動擷取伸縮容器中剩餘的空間。 所以設定垂直方向`margin`值為`auto`,可以使伸縮項目在伸縮容器的兩上軸方向都完全集中。 */ </style></head><body> <div class="parent"> <div class="child">ff</div> </div></body></html>
未知寬高元素實現水平垂直置中方案
使用transform:translate屬性來調整
代碼
index.html
<!DOCTYPE html><html lang="zh"><head> <meta charset="UTF-8"> <title>塊狀元素水平垂直置中(未知寬高)</title> <style> *{margin: 0;padding: 0;} /*簡易版reset,工作環境不推薦使用*/ #container{ position:absolute; top:50%; left:50%; -webkit-transform: translate(-50%,-50%); -ms-transform: translate(-50%,-50%); -o-transform: translate(-50%,-50%); transform: translate(-50%,-50%); background-color: #A4FF00; color:rgb(33, 172, 134); } /*因為不知道寬高度,所以主要用translate屬性拉回未知元素XY軸上的位置實現置中*/ /*若是單純實現未知高度的元素置中,只要用到transform:translateY(-50%)即可實現*/ </style></head><body> <div id="container">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae obcaecati expedita ducimus, rem laborum veniam qui quo facilis enim. Repellat blanditiis nemo, magnam, sequi illum perferendis consequatur modi maiores quaerat?</div></body></html>
flex實現頁面水平垂直置中方案
定義置中元素的父元素justify-content和align-items屬性為center即可,
需要設定足夠的高度,不然只有水平置中效果
代碼實現
index.html
<!DOCTYPE html><html lang="zh"> <head> <meta charset="UTF-8"> <title>flex實現子塊的完美置中</title> <style> * { margin: 0; padding: 0; } .parent { display: flex; justify-content: center; align-items: center; height:900px; background: #03A1FA; } .child { width: 100px; height: 100px; background: #BB3713; } </style> </head> <body> <div class="parent"> <div class="child">啦啦德瑪新亞</div> </div> </body></html>