原文 http://neirong.org/post-260.html
有兩個嵌套關系的div,如果外層div的父元素padding值為0,那么內層div的margin-top或者margin-bottom的值會“轉移”給外層div,使父元素產生上外邊距。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>無標題文檔</title> </head> <body> <div style="width:300px; height:100px">上部層</div> <div style=" width:300px; height:300px;overflow:hidden "> <!--父層--> <div style="margin:50px; width:200px; height:200px"">子層</div> </div> </body> </html>
原因:盒子沒有獲得 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
父層div加:position: absolute;
