css外邊距疊加條件:
必須是普通文檔流中的塊框的垂直外邊距相互接觸才會發(fā)生外邊距疊加乎赴,
注意:外邊距必須相互接觸才能疊加
疊加理由:處于塊級格式化上下文中, 垂直接觸的外邊距會疊加
疊加的情況有三種:
- 同級元素直接外邊距疊加
- 父和子之間外邊距疊加
- 自己和自己之間外邊距疊加
情況1 同級元素直接外邊距疊加
<div class="p1"></div>
<div class="p2"></div>
.p1 {
width: 100px;
height: 100px;
background: red;
margin-bottom: 30px;
}
.p2 {
width: 100px;
height: 100px;
background: red;
margin-top: 30px;
}
結(jié)果為
Paste_Image.png
兩個元素直接為 30px, 即發(fā)生了外邊距的重疊
如何解決呢概漱?
之前說過,在BFC中 色冀,垂直方向上,接觸的外邊距會發(fā)生外邊距疊加关斜,一種簡單的思路就是炭菌,不然兩個外邊距接觸,即
<div class="p1"></div>
<hr/>
<div class="p2"></div>
Paste_Image.png
發(fā)現(xiàn)外邊距不疊加了却舀,另外一種方法是虫几,利用BFC, 讓兩個元素不在同一個BFC里面
<div class="p1"></div>
<div class="bfc">
<div class="p2"></div>
</div>
.p1 {
width: 100px;
height: 100px;
background: red;
margin-bottom: 30px;
}
.p2 {
width: 100px;
height: 100px;
background: red;
margin-top: 30px;
}
.bfc {
overflow: hidden;
}
Paste_Image.png
簡單的說就是挽拔,讓P2 處于 div.bfc這個BFC上下文里面辆脸,從而與 P1不在一起
情況2 父和子之間外邊距疊加
<div class="p"></div>
<div class="parent">
<div class="child"></div>
</div>
.p {
width: 100px;
height: 100px;
background: red;
}
.parent {
width: 100px;
height: 100px;
background: red;
margin-top: 20px;
}
.child {
width: 100px;
height: 100px;
background: yellow;
margin-top: 60px;
}
Paste_Image.png
發(fā)現(xiàn),p 和 parent之間的外邊距為60螃诅, 這是為啥啡氢,因為parent 和 child的外邊距 發(fā)生了接觸状囱,所以他們疊加了, 解決方法也很簡單倘是,讓parent和child的外邊距不接觸就行了亭枷,于是給parent加一個外邊距
.parent {
width: 100px;
height: 100px;
background: red;
margin-top: 20px;
border-top: 1px solid green;
}
Paste_Image.png
發(fā)現(xiàn)加了外邊距后, child的margin部分也成為了 parent的一部分辨绊,這里好涉及到另外一個點 究竟元素真正的邊框是啥,其實是外邊距匹表,只是外邊距之間的疊加门坷, 而且外邊距不顯示背景色讓我們誤以為 外邊距不算是不算是元素的一部分, 但實際上袍镀,外邊距才是元素的真正邊距
情況3 自己和自己外邊距疊加
如果一個元素默蚌,margin-bottom 和 marginp-top之間沒有內(nèi)容,相互接觸的話苇羡,他們也會疊加
<div class="top"></div>
<div class="middle"></div>
<div class="bottom"></div>
.top, .bottom {
width: 100px;
height: 100px;
background: red;
}
.bottom {
background: yellow;
}
.middle {
margin-top: 30px;
margin-bottom: 30px;
}
Paste_Image.png
發(fā)現(xiàn)上 和 下兩個元素只有30px邊距绸吸,說明,middle自己的 margin-top和marign-bottom發(fā)生了疊加设江,如何解決呢锦茁, 讓他們不接觸即可
.middle {
margin-top: 30px;
margin-bottom: 30px;
border-top: 1px solid transparent;
}
Paste_Image.png