子元素设置margin-top,父元素无法将margin-top包含在父容器的原因及解决办法

代码如下: layout
结果:父级并没有完全保住子集,父级没有包含子集的margin-top部分, 原因:CSS2.1的盒模型中规定: 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分隔。 CSS2.1规定浮动元素和绝对定位元素不参与Margin折叠 所以解决办法为: 1.给.parent设置padding 或 border 2.给parent设置float或position:absolute( 别忘记设置宽度,他们已经脱离文档流了) 3.给parent设置overflow:hidden/auto/overlay/scroll 建议使用hidden(scroll会出现滚动条)
原文地址:https://www.cnblogs.com/jingjing0518/p/7792474.html