1. 程式人生 > >margin到底相對誰?

margin到底相對誰?

margin垂直方向上存在以下問題:

  • 外邊距合併現象
    • 如果兩個div上下排列,給上面div設定margin-bottom,給下面div設定margin-top,那麼兩個margin會發生合併現象,會取較大的margin值。
    • 注意:左右不會發生 外邊距合併現象
  • 上下塌陷現象
    • 一個大盒子 中包含一個小盒子,給小盒子設定一個margin-top,大盒子會一起向下平移。
    • 注意:margin左右沒有塌陷現象

如果父元素在子元素的margin的同向上有padding或border的話,子元素的margin相對於父元素,否則相對於父元素以外的元素。

上面這句總結不要記住,理解原理:就是BFC

,可以參考我的一篇部落格:高度坍塌問題-BFC解析

我們還是看例子吧:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>margin</title>
<style type="text/css">
    .parent{width: 300px;line-height: 1.8; outline: 1px dashed red;}
    .sample{height: 150px;background-color: pink;}
    .sb
{width: 300px;height: 150px;background-color: #0ff;} .sample{margin-bottom: 50px;}
</style> </head> <body> <div class="parent"> <div class="sample">sample</div> </div> <div class="sb">after</div> </body> </html>

此時父元素在子元素的margin的同向上(bottom)沒有padding或border,子元素的margin相對於父元素以外的元素。紅色框包圍的是父元素,效果如圖:

這裡寫圖片描述

這個時候,如果給父元素新增下邊框(與子元素margin同向)的話,css為:.parent{border-bottom: 5px solid red;} 那麼子元素的margin相對於父元素。效果如下:

這裡寫圖片描述

如果我們不加邊框而是增加下內邊距(與子元素margin同向)的話,css為:.parent{padding-bottom: 50px;}
那麼子元素的margin相對於父元素(為了看到內邊距效果,可以在父元素上設 .parent{outline: 1px dashed red;})。效果如下:

這裡寫圖片描述

padding或者border會產生BFC,此外還有很多情況會產生BFC,但是padding和border只會產生對應方向上的。比如我這裡只設置padding-bottom,若子元素還有margin-top:10px、那麼top仍然會產生這個現象。

最後,真的好好理解BFC。