一、利用table属性,设置display
布局为:
<div id="father">
<div id="child">
</div>
</div>
样式为:
#father{
width: 200px;
height: 200px;
background: red;
display: table-cell;
vertical-align:middle;
text-align: center;
}
#child{
width: 50px;
height: 50px;
background: green;
display: inline-block;
}
二、绝对定位法(一)
原理:先把这个定位元素的left和top设置为50%,此时它并未居中,只是相对于居中位置向右和向下偏移了自身长宽的一半。然后为其设置负的margin-left和margin-top将其拉回居中的位置,具体值为其自身长宽的一半。
布局为:
<div id="father">
<div id="child">
</div>
</div>
样式为:
#father{
width: 200px;
height: 200px;
background: red;
position: relative;
}
#child{
width: 50px;
height: 50px;
background: green;
position: absolute;
left: 50%;top:50%;
margin-left: -25px;
margin-top: -25px;
}
三、绝对定位法(二)
布局为:
<div id="father">
<div id="child">
</div>
</div>
样式为:
#father{
width: 200px;
height: 200px;
background: red;
position: relative;
}
#child{
width: 50px;
height: 50px;
background: green;
position: absolute;
left:0;right:0;top:0;bottom:0;
margin: auto;
}