居中樣式,都是比較常用的方法,不常用的就不舉例了 有這幾種就夠用了
1/2 都是固定寬高
3 個人覺得是最好用的,可以不考慮寬高問題
-
text-align:center;
<div class="box"> <span>測試文字</span> </div>
.box{ width:120px; height:100px; background:#000; text-align: center; line-height:100px; }
-
margin:auto;
- 居中元素必須是塊元素
<div class="box"> <span>測試文字</span> </div>
.box{ background: #000; color: #FFF; width: 120px; height: 70px; padding-top: 30px; } .box span{ display: block; width: 64px; border: 1px solid #fff; margin: auto; }
- 定位元素
<div class="box"> <span>測試文字</span> </div>
.box{ background: #000; color: #FFF; width: 120px; height: 100px; position: relative; } .box span{ width: 64px; height: 24px; position: absolute; border: 1px solid #fff; left: 0; right: 0; top: 0; bottom:0; margin: auto; }
- 居中元素必須是塊元素
-
transform: translate(-50%,-50%);
<div class="box"> <span>測試文字</span> </div>
css有兩種方法(margin/position)
- 需要明確box的寬高
.box{ background: #000; color: #FFF; width: 140px; height: 100px; } .box span{ border: 1px solid #fff; float: left; margin: 50px 0 0 70px; transform: translate(-50%,-50%); }
- 不用計算外層寬高,需要用到定位
.box{ background: #000; color: #FFF; width: 140px; height: 100px; position: relative; } .box span{ border: 1px solid #fff; position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); }
- 需要明確box的寬高
大圖片左右居中參考本人另外一篇文章
超出容器的圖片在容器裏左右居中,不使圖片變形(大圖片居中問題)