HTML
<div class="father">
<div class="son"></div>
</div>
1、利用 absolute 和 translate
CSS
.father{
position: relative;
margin: 0 auto;
width: 200px;
height: 200px;
background: red;
}
.son{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100px;
height: 100px;
background: blue;
}
2、利用 absolute 和 負(fù)的margin
CSS
.father{
position: relative;
margin: 0 auto;
width: 200px;
height: 200px;
background: red;
}
.son{
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
background: blue;
}
3、利用 absolute 和 top right bottom left 和 margin: auto
CSS
.father{
position: relative;
margin: 0 auto;
width: 200px;
height: 200px;
background: red;
}
.son{
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
width: 100px;
height: 100px;
background: blue;
}
4、利用 display: table 和 display: table-cell
(1)
display: table時padding會失效
(2)display: table-row時margin、padding同時失效
(3)display: table-cell時margin會失效
(4) 表格中的單元格中的div設(shè)置寬度無效,是因為div被設(shè)置為display: table-cell,后將其修改為display: block則設(shè)置的寬度生效
CSS
.father{
display: table-cell;
text-align: center;
vertical-align: middle;
width: 200px;
height: 200px;
background: red;
}
.son{
display: inline-block;
width: 100px;
height: 100px;
background: blue;
}
效果

table-cell 居中
5、通過 font-size 實現(xiàn)居中
IE7 以下有效
font-size值為height / 1.14
HTML
<div class="father">
<span class="son"></span>
</div>
CSS
.father{
width: 200px;
height: 200px;
font-size: 175.4px; /* height / 1.14 */
text-align: center;
background: red;
}
.son{
display: inline-block;
zoom: 1;
vertical-align: middle; /*inline 和 inline-block 才能設(shè)置該屬性*/
font-size: 12px; /* 初始化字體大小 */
width: 100px;
height: 100px;
background: blue;
}