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

#div1{

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

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




帮忙分析下这段代码是如何实现居中的,多谢。
阅读 7.7k
1 个回答
  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>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进