1. 程式人生 > >為什麼第一個子元素設定margin-top父元素會跟著移動(附解決方案)

為什麼第一個子元素設定margin-top父元素會跟著移動(附解決方案)

問題:
有時當我們設定子元素的margin-top,但是卻發現子元素沒有出現上外邊距的效果,反而是父元素出現了上外邊距的效果。
原因:
邊距重疊:一個盒子和其子孫的邊距重疊。根據規範,一個盒子如果沒有上補白和上邊框,那麼它的上邊距應該和其文件流中的第一個孩子元素的上邊距重疊。
解決方案
1、為父元素設定padding。

#father {
    width: 300px;
    height: 300px;
    background: orange;
    padding: 1px;
}
#son {
    width: 100px;
    height: 100px;
    margin: 50px;
    background: red;
}

2、為父元素設定border。

	#father {
	    width: 300px;
	    height: 300px;
	    background: orange;
	    border: 1px solid #000;
	}
	#son {
	    width: 100px;
	    height: 100px;
	    margin: 50px;
	    background: red;
	}

3、為父元素設定 overflow: hidden 。

#father {
    width: 300px;
    height: 300px;
    background: orange;
    overflow: hidden;
}
#son {
    width: 100px;
    height: 100px;
    margin: 50px;
    background: red;
}

4、父級或子元素使用浮動或者絕對定位absolute

#father {
    width: 300px;
    height: 300px;
    background: orange;
    position:absolute;
}
#son {
    width: 100px;
    height: 100px;
    margin: 50px;
    background: red;
}