问题:
有父元素div[#parent],有子元素div[#child],用css实现子元素在父元素中”水平垂直居中”
<div id="parent">
<div id="child"></div>
</div>
效果描述:
方案实现:
方案1
#parent{
width: 220px;
height: 220px;
background-color: #B94D55;
position: relative;
}
#child{
width: 100px;
height: 100px;
background-color: #B99D4D;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
方案2
#parent{
width: 220px;
height: 220px;
background-color: #B94D55;
position: relative;
}
#child{
width: 100px;
height: 100px;
background-color: #B99D4D;
position: absolute;
top: 50%;
left: 50%;
/*css3*/
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
}
当然,用fixed定位也是可以实现的,细心的同学可以发现,方案1和方案2的区别仅仅是移动的方式不同(margin和translate),那么方案1和方案2有什么区别吗?
区别:
- 方案1的margin无兼容性,方案2的css3有兼容性
- 方案2的的优点:当子元素div[#child]不知形状(宽高)时,方案2就可以实现
方案3
#parent{
width: 220px;
height: 220px;
background-color: #B94D55;
/*flex*/
display: -webkit-flex;
display: flex;
justify-content: center;
align-items: center;
}
#child{
width: 100px;
height: 100px;
background-color: #B99D4D;
}
这个的实现原理是flex布局,这里有个很不错的教程 前往