塊的頂部外邊距和底部外邊距有時被組合(折疊)為單個外邊距,其大小是組合到其中的最大外邊距,這種行為稱為外邊距塌陷(margin collapsing),有的地方翻譯為外邊距合并。
發生外邊距塌陷的三種基本情況:
-
相鄰的兄弟姐妹元素垂直方向外邊距合并
毗鄰的兩個兄弟元素之間的外邊距會塌陷(除非后者兄弟姐妹需要清除過去的浮動)。例如:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<style>
body {
background: yellow;
}
div {
width: 100px;
height: 100px;
border: 1px solid;
margin: 50px;
}
</style>
</head>
<body>
<div class="d1">d1</div>
<div class="d2">d2</div>
</body>
</html>
測試01.png
但是后者清除浮動后則不會合并:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<style>
div {
width: 100px;
height: 100px;
border: 1px solid;
margin: 50px;
float: left;
}
.d2 {
content: "";
display: both;
clear: both;
}
</style>
</head>
<body>
<div class="d1">d1</div>
<div class="d2">d2</div>
</body>
</html>
測試02.png
-
塊級父元素與其第一個/最后一個子元素
如果塊級父元素中,不存在上邊框、上內邊距、內聯元素、清除浮動這四條屬性(也可以說,當上邊框寬度及上內邊距距離為0時),那么這個塊級元素和其第一個子元素的上邊距就可以說”挨到了一起“。此時這個塊級父元素和其第一個子元素就會發生上外邊距合并現象,換句話說,此時這個父元素對外展現出來的外邊距將直接變成這個父元素和其第一個子元素的margin-top的較大者。如:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<style>
body {
background: yellow;
}
.d1,.ct {
width: 200px;
height: 100px;
background: blue;
margin-top: 50px;
}
.d2 {
width: 50px;
height: 50px;
background: red;
margin-top: 50px;
}
</style>
</head>
<body>
<div class="d1">d1</div>
<div class="ct">
<div class="d2">d2</div>
</div>
</body>
</html>
測試03.png
類似的,若塊級父元素的 margin-bottom 與它的最后一個子元素的margin-bottom 之間沒有父元素的 border、padding、inline content、height 、min-height 、max-height 分隔時,就會發生下外邊距合并 現象。
-
空塊元素
如果存在一個空的塊級元素,其 border、padding、inline content、height 、min-height 都不存在。那么此時它的上下邊距中間將沒有任何阻隔,此時它的上下外邊距將會合并。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<style>
body {
background: yellow;
}
.d1,.d3 {
width: 300px;
height: 50px;
background: red;
}
.d2 {
margin-top: 50px;
margin-bottom: 50px;
}
</style>
<body>
<div class="d1">d1和d2相距50px</div>
<div class="d2"></div>
<div class="d3">d1和d2相距50px</div>
</body>
</html>
測試04.png
合并規則:
- 兩個margin都是正值的時候,取兩者的最大值;
- 當 margin 都是負值的時候,取的是其中絕對值較大的,然后,從0位置,按文檔流負向位移;
- 當有正有負的時候,先取出負 margin 中絕對值中最大的,然后,和正 margin 值中最大的 margin 相加。
- 所有毗鄰的margin要一起參與運算,不能分步進行。
不讓相鄰元素外邊距合并的方法:
- 被非空內容、padding、border 或 clear 分隔開。
- 不在一個普通流中或一個BFC中。
- margin在垂直方向上不毗鄰。
例外的情況:
根元素的外邊距不會參與折疊
不設置任何屬性的空span和空div不影響任何布局,可以無視之。