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
和 负的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
设置宽度无效,是因为div
被设置为display: table-cell
,后将其修改为display: block
则设置的宽度生效
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
实现居中
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 才能设置该属性*/
font-size: 12px; /* 初始化字体大小 */
width: 100px;
height: 100px;
background: blue;
}
网友评论