方法1、 CSS3 transform和position(元素寬高未知的狀況)
<div class="box">
<span>寬高未知</span>
</div>
.box {
width: 400px;
height: 400px;
background: #ccc;
position:relative;
}
.box span {
background: red;
position: absolute;
left: 50%;
top: 50%;
color: #fff;
transform: translate(-50%, -50%);
}
方法2、 絕對定位和margin-left:-自身寬度一半,margin-top: -自身高度的一半 (已知寬高)
<div class="box">
<span>寬高已知</span>
</div>
.box {
width: 400px;
height: 400px;
background: #ccc;
position: relative;
}
.box span {
display: inline-block;
width: 100px;
height: 100px;
background: red;
text-align: center;
line-height: 100px;
position: absolute;
left: 50%;
top: 50%;
color: #fff;
margin-left: -50px;
margin-top: -50px;
}
方法3、 css3 flex佈局
<div class="box">
<div class="child"></div>
</div>
.box {
width: 400px;
height: 400px;
background: #ccc;
display:flex;
justify-content:center;
align-items: center;
}
.box .child {
display: inline-block;
width: 100px;
height: 100px;
background: red;
}
方法4、 被居中的元素是inline或者inline-block元素
<div class="box">
<span class="child">inline和inline-block元素</span>
</div>
.box {
width: 400px;
height: 400px;
background: #ccc;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.box .child {
display: inline-block;
width: 100px;
height: 100px;
background: red;
}
方法5、絕對定位和margin:auto
<div class="box">
<div class="child">定高</div>
</div>
.box {
width: 400px;
height: 400px;
background: #ccc;
position: relative;
}
.box .child {
width: 100px;
height: 100px;
background: red;
text-align: center;
color: #fff;
line-height: 100px;
position: absolute;
top:0;
right:0;
bottom:0;
left:0;
margin: auto;
}
方法6、line-height: 父級高度和text-align: center
<div class="box">
<span class="child">line-height</span>
</div>
.box {
width: 400px;
height: 400px;
background: #ccc;
line-height: 400px;
text-align: center;
font-size: 0;
}
.box .child {
background: red;
font-size: 14px;
color: #fff;
}