开发者社区> 问答> 正文

关于margin折叠的一个问题。

![screenshot](https://oss-cn-hangzhou.aliyuncs.com/yqfiles/e6f53e955566b99ce786890c9b4592a04027e8b6.png)
<html>
<head>
    <style>
        * {padding: 0; margin: 0;}
        #b1 {
            width: 300px;
            height: 100px;
            margin-bottom: 4em;
            background-color: #0d8ba1;
        }
        #F {
            float: left;
            width: 100px;
            height: 70px;
            background-color: yellow;
        }
        #b2 {
            /*clear: both;*/
            width: 300px;
            height: 100px;
            background-color: red;
            margin-top: 2em;
        }
    </style>
</head>
<body>
<div id="b1"></div>
<div id="F"></div>
<div id="b2"></div>
</body>
</html>

运行时,对比#b2有clear:both与没clear:both时,b1与b2margin的折叠情况。

设置clear:both之后,#b2为了避开浮动的F,往下移动,出现了clearance也就是空隙,b1与b2不再折叠!

另外,stack overflow那个家伙的答案我没再细究。pass。

展开
收起
杨冬芳 2016-06-13 10:36:02 2151 0
1 条回答
写回答
取消 提交回答
  • IT从业

    collapsing margins
    基本上这节意思是说,比邻元素的边距总是折叠。

    但是得除了以下几种情况:
    •Margins of the root element's box do not collapse.(根元素不折叠)

    •If the top and bottom margins of an element with clearance are adjoining, its margins collapse with the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block.(有间隙不折叠)

    •Margins between a floated box and any other box do not collapse (not even between a float and its in-flow children). (浮动不折叠)
    •Margins of elements that establish new block formatting contexts (such as floats and elements with 'overflow' other than 'visible') do not collapse with their in-flow children.(创建BFC与子不折叠)
    •Margins of absolutely positioned boxes do not collapse (not even with their in-flow children).(positioned 不折叠)
    •Margins of inline-block boxes do not collapse (not even with their in-flow children).(inline-box 不折叠)
    •The bottom margin of an in-flow block-level element always collapses with the top margin of its next in-flow block-level sibling, unless that sibling has clearance.(兄弟有间隙不折叠)
    •The top margin of an in-flow block element collapses with its first in-flow block-level child's top margin if the element has no top border, no top padding, and the child has no clearance.(父子间有padding 和 border 不折叠)
    楼主所问问题不在这些情况内,所以会合并边距。

    求折叠。

    2019-07-17 19:35:15
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载