Centered style, are more commonly used method, it does not have the conventional example is not enough to use these types of
1/2 of the width and height are fixed
3 people think it is best to use, you can not consider the width and height issue
-
text-align:center;
<div class="box"> <span>测试文字</span> </div>
.box{ width:120px; height:100px; background:#000; text-align: center; line-height:100px; }
-
margin:auto;
- Element is a block element must be centered
<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; }
- Positioned elements
<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; }
- Element is a block element must be centered
-
transform: translate(-50%,-50%);
<div class="box"> <span>测试文字</span> </div>
There are two methods css (margin / position)
- We need to be clear box width and height
.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%); }
- Without calculation outer width and height, the positioning need to use
.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%); }
- We need to be clear box width and height