1. 程式人生 > >HTML:margin塌陷現象的解決

HTML:margin塌陷現象的解決

設定子元素的margin,父元素也具有與子元素相同的margin值,稱之為塌陷現象。這種現象我們稱之為margin的塌陷現象。具體說就是子類標籤設定margin-top:50px;時,不是子類標籤距離父類標籤上邊框50畫素。而是子類標籤和父類標籤距離上級標籤50個畫素。比如下圖程式碼就會導致塌陷現象:

<style type="text/css">
div.father{
width: 200px;
height: 200px;
background: #FFC0CB;
}
div.son{
width: 100px;
height: 100px;
background: beige;
margin-top:50px;
}
</style>

<div class="father">
<div class="son"></div>

</div>

效果圖:


而解決margin塌陷現象有兩種方法:

方法一:在父類標籤設定overflow:hidden;屬性

程式碼:

<style type="text/css">
div.father{
width: 200px;
height: 200px;
background: #FFC0CB;
overflow: hidden;
}
div.son{
width: 100px;
height: 100px;
background: beige;
margin-top:50px;
}

</style>

<div class="father">
<div class="son"></div>
</div>

效果圖:


方法二:給父類標籤設定border屬性即可。

程式碼:

<style type="text/css">
div.father{
width: 200px;
height: 200px;
background: #FFC0CB;
border: 1px solid #000000;/*不需要邊框的時候可以將背景顏色設為透明或者與背景顏色相同的顏色*/
}
div.son{
width: 100px;
height: 100px;
background: beige;
margin-top:50px;
}
</style>

<div class="father">
<div class="son"></div>
</div>

效果圖: