問題描述
今天在修改頁面樣式的時(shí)候,遇到子元素設(shè)置margin-top 但是并沒有使得子元素與父元素之間產(chǎn)生間隔,而是作用在了其父元素上,導(dǎo)致父元素產(chǎn)生了一個(gè)margin-top 的效果。
今天就來說說整個(gè)問題產(chǎn)生的原因,以及解決方案。
問題分析
在MDN上面有這么一段文字:
塊的上外邊距(margin-top )和下外邊距(margin-bottom )有時(shí)合并(折疊)為單個(gè)邊距,其大小為單個(gè)邊距的最大值,這種行為稱為邊距折疊 。
注意:只有上下邊距會產(chǎn)生折疊,左右邊距不會產(chǎn)生折疊。
有三種情況會產(chǎn)生邊距折疊:
1、同一層相鄰元素之間
<div class="A">元素A</div>
<div class="B">元素B</div>
<style>
.A,
.B {
width: 50px;
height: 50px;
}
.A {
background: yellow;
margin-bottom: 10px;
}
.B {
background: pink;
margin-top: 20px;
}
</style>
上面兩個(gè)p標(biāo)簽之間的間隔是20px。

解決辦法:
第二個(gè)元素B,設(shè)置清除浮動clearfix
.clearfix::after {
content: "";
display: block;
clear: both;
height: 0;
overflow: hidden;
visibility: hidden;
}
.clearfix {
zoom: 1;
}
2、父子元素之間沒有內(nèi)容
例子中,A,B元素與父元素box之間沒有其他元素的情況下:
<div class="box">
<div class="A">元素A</div>
<div class="B">元素B</div>
</div>
<div class="next">Next</div>
<style>
.box {
margin-top: 10px;
margin-bottom: 10px;
background: #eee;
}
.A,
.B {
width: 50px;
height: 50px;
}
.A {
background: yellow;
margin-top: 20px;
}
.B {
background: pink;
margin-bottom: 20px;
}
.next {
height: 50px;
background: #eee;
}
</style>

解決辦法:
- 父元素創(chuàng)建塊級格式上下文(
overflow:hidden )
- 父元素設(shè)置上下border(
border: 1px solid transparent )、
- 父元素設(shè)置上下padding(
padding: 1px 0 )
- 子元素采用浮動
float 或者定位position 的方式排列。
注意:即使設(shè)置父元素的外邊距是0,margin: 0 ,第一個(gè)或最后一個(gè)子元素的外邊距仍然會“溢出”到父元素的外面。
3、空的塊級元素
當(dāng)元素B的margin-top 直接貼到元素A的margin-bottom 的時(shí)候(也就是中間的元素沒有內(nèi)容),也會發(fā)生邊界折疊。
<div class="top">top</div>
<div class="middle"></div>
<div class="bottom">bottom</div>
<style>
.top,.bottom {
width: 50px;
height: 50px;
background: pink;
}
.middle {
margin-top: 10px;
margin-bottom: 20px;
}
</style>

解決方法:
-
middle元素清除浮動: clearfix
-
middle元素創(chuàng)建塊級格式上下文:overflow:hidden
-
middle元素設(shè)置為行內(nèi)塊元素: display: inline-block;
-
middle元素設(shè)置高度: height: 1px;
-
middle元素設(shè)置最小高度:min-height: 1px;
-
middle元素設(shè)置border:border-top: 1px solid transparent;
-
middle元素設(shè)置padding:padding-top: 1px;
注意事項(xiàng)
- 如果參與折疊的margin中包含負(fù)值,折疊后的margin的值為
最大的正邊距與最小的負(fù)邊距(即絕對值最大的負(fù)邊距)的和 ;也就是說如果有-10px,10px,30px疊在一起,margin的范圍就是 30px-10px=20px。
- 如果所有參與折疊的外邊距都為負(fù),折疊后的外邊距的值為
最小的負(fù)邊距的值 。這一規(guī)則適用于相鄰元素和嵌套元素。
參考鏈接
原文首發(fā)地址:https://github.com/Daotin/fe-blog/issues/
你也可以從下面地方找到我:
|