笔记:嵌套层magrin失效的问题(转移给外层div)

228 阅读1分钟

有两个嵌套关系的div,如果给子div设置margin-top或者margin-bottom,其值会转移给外层div

原因:盒子没有获得 haslayout 造成 margin-top无效

解决办法:

1、在父层div加上:overflow:hidden;

2、把margin-top外边距改成padding-top内边距 ;

3、父元素产生边距重叠的边有不为 0 的 padding 或宽度不为 0 且 style 不为 none 的 border。

父层div加: padding-top: 1px;

4、让父元素生成一个 block formating context,以下属性可以实现

* float: left/right
* position: absolute
* display: inline-block/table-cell(或其他 table 类型)
* overflow: hidden/auto