使用css居中有不少種方式,在這裏寫幾個最佳實踐。代碼簡單粗暴,適用性強,讓你沒必要這點小事煩惱,提高你的工做效率,早幾分鐘下班回家LOL豈不是美滋滋
很少說廢話,直接上代碼css
<div class="container"> <div class="inner"> </div> </div>
.container { height: 200px; width: 200px; background: #369; } .inner { height: 50px; width: 50px; background: #963; }
<p>左右居中1</p> <div class="container center1"> <div class="inner center-inner1"> </div> </div> <p>左右居中2</p> <div class="container center2"> <div class="inner"> </div> </div>
.center1 { text-align: center; } .center-inner1 { display: inline-block; } .center2 { display: flex; justify-content: center; } .center-inner2 { display: inline-block; }
<p>垂直居中1</p> <div class="container center3"> <div class="inner center-inner3"></div> </div> <p>垂直居中2</p> <div class="container center4"> <div class="inner center-inner4"></div> </div>
.center3 { display: flex; align-items: center; } .center4 { position: relative; } .center-inner4 { position: absolute; top: 50%; transform: translateY(-50%); }
<p>左右居中+垂直居中</p> <div class="container center5"> <div class="inner"></div> </div>
.center5 { display: flex; align-items: center; justify-content: center; }
點個收藏關注一下不迷路佈局