CSS外邊距合併
外邊距合併
使用margin定義塊元素的垂直外邊距時,可能會出現外邊距的合併。
一、相鄰塊元素垂直外邊距的合併
當上下相鄰的兩個塊元素相遇的時候,如果上面的元素有下外邊距margin-bottom,下面的元素有上外邊距margin-top,則他們之間的垂直間距並不是margin-bottom加上margin-top之和,而是兩者之間的較大者,這種現象被稱之爲相鄰塊元素垂直外邊距的合併(或外邊距塌陷)。
如上圖所示,外邊距合併形成一個外邊距(最終兩個盒子的距離以數值大的爲準)。
其實這是一個瀏覽器的Bug,日常工作中我們應該儘量避免。
【實例代碼】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>外邊距合併</title>
<style>
div {
width: 300px;
height: 200px;
background-color: purple;
}
.one {
margin-bottom: 100px;
}
.two {
background-color: pink;
margin-top: 50px;
}
</style>
</head>
<body>
<div class="one">One</div>
<div class="two">Two</div>
</body>
</html>
二、嵌套塊元素垂直外邊距的合併
對於兩個嵌套關係的塊元素,如果父元素沒有上內邊距及邊框,則父元素的上外邊距會與子元素的上外邊距發生合併,合併後的外邊距爲兩者中的較大者,即使父元素的上外邊距爲0,這種情況也會發生。
解決方案:
- 1、可以爲父元素定義1像素的上邊框或上內邊距;
border-top: 1px solid purple;
padding-top: 1px;
但是這個方法增大了盒子,需要在width中減去;
- 2、可以爲父元素添加overflow:hidden(溢出隱藏);
【實例代碼】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.one {
width: 500px;
height: 500px;
background-color: purple;
/*border-top: 1px solid purple;
padding-top: 1px;*/
overflow: hidden;
}
.two {
width: 200px;
height: 200px;
background-color: pink;
margin-top: 50px;
margin-left: 50px;
}
</style>
</head>
<body>
<div class="one">
<div class="two"></div>
</div>
</body>
</html>