子容器margin-top为何会影响父容器位置

  子容器设置css设置margin-top,如果子容器和父容器直接没有内容,由于css盒式模型,将会导致子容器和父容器的margin-top叠加,导致父容器也会继承子容器的margin-top,导致父容器顶部出现空白。

  示例代码如下,cs父容器aa继承了cs设置的martin-top

子容器margin-top为何会影响父容器位置

<!doctype html>
<style>
    .main{margin-left:100px;width:500px;height:500px;border:solid 1px green;}
    .aa{width:100px;height:100px;background:orange;position:relative;}
    .cs{width:50px;height:50px;margin-top:10px;background:#000}
    .cc{width:20px;height:20px;background:#f00}
</style>
<div class="main">
    <div class="aa"><!--内容-->
        <div class="cs">
            <div class="cc"></div>
        </div>
    </div>
</div>

  CSS2.1的盒模型中规定的内容——Collapsing margins

In this specification, the expression collapsing margins means that adjoining margins (no non-empty content, padding or border areas or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin. 所有毗邻的两个或更多盒元素的margin将会合并为一个margin共享之。毗邻的定义为:同级或者嵌套的盒元素,并且它们之间没有非空内容、 Padding或Border分隔。
来源:http://www.cnblogs.com/hejia/archive/2013/05/26/3099697.html

  解决办法:父容器增加 padding/border,或者将 父容器 / 子容器 样式 float:left/right或者position:absolute定位(CSS2.1规定浮动元素和绝对定位元素不参与Margin折叠)。

.aa{width:100px;height:100px;background:orange;position:relative;border:solid 1px #eee}

 

加支付宝好友偷能量挖...


原创文章,转载请注明出处:子容器margin-top为何会影响父容器位置

评论(0)Web开发网
阅读(286)喜欢(0)HTML/CSS兼容/XML