在web开发过程中,有些情况下给内层div设置的margin却被莫名奇妙的转移给了外层div。百度之后,发现它竟然是CSS 2.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分隔
解决办法:
给父元素添加
overflow: hidden
属性或者给父元素添加
padding-top
属性,属性值为要设定的margin
值