首页 > 浮动元素垂直居中的一些疑问

浮动元素垂直居中的一些疑问

#div1{

width: 200px;
height: 200px;
background-color: #6699FF;

margin:auto;
position: absolute;        //父元素需要相对定位
left: 0;
top: 0;
right: 0;
bottom: 0;
}




帮忙分析下这段代码是如何实现居中的,多谢。

  1. 通过 widthheight 限制大小,从而在父元素和子元素间留出空间;

  2. 通过 position, marginleft 让子元素的外边距等分了留出的空间,从而达到居中的效果。

附上在 Firefox 中实测有效的代码:

<!-- index.html -->
<style>
    #child {
        width: 200px;
        height: 200px;
        background-color: #6699FF;

        margin:auto;
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
    }
</style>

<div id="parent">
    <div id="child"></div>
</div>
【热门文章】
【热门文章】