居中样式,都是比较常用的方法,不常用的就不举例了 有这几种就够用了
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的宽高