統一的解決方案;設置padding或者border或者觸發BFC
首先把全部的margin格式清空html
<head> <title>邊距重疊</title> <style> html *{ margin-top: 0px; padding: 0px; } </style> </head> <body>
1.父子元素之間
塊級父元素與第一個或者最後一個子元素(父元素不存在上邊框、上內邊距、內聯元素、清除浮動)。即這個父元素對外展示出來的外邊距將直接變成這個父元素和其第一個子元素的margin-top的較大者。父元素的高度:100 或者110 都對.沒有overflow: hidden的時候父邊距和子邊距重疊了,父的高度只有100.加了overflow: hidden,父元素成了新的bfc,就解決了邊距重疊的現象,margin-top 沒有塌陷進去,因此父的高度是110px;佈局
<section id="parentAndChild"> <style> .parent { background-color: red; /*overflow: hidden;*/ } .child { height: 100px; margin-top: 10px; background-color: yellow; } </style> <div class="parent"> <div class="child"></div> </div> </section>
2.相鄰兄弟姐妹元素post
兩個div的邊距是50px 而不是90,取了最大值,若爲負值,則取絕對值最大的,若一正一負,則取二者的和。
<section > <style> .left{ height: 100px; margin-bottom: 50px; background-color: red; } .right{ height:100px; background-color: blue; margin-top: 40px; } </style> <div class="left"></div> <div class="right"></div> </section>
3.空塊元素
若是存在一個空的塊級元素, border、 padding、 inline content 、height 、min-height 都不存在,那麼上下邊距居中將沒有任何阻礙,上下邊距將合併。取值規則同2同樣flex
<section> <p style="margin-bottom: 0px;">這個段落的和下面段落的距離將爲20px</p> <div style="margin-top: 20px; margin-bottom: 50px;"></div> <p style="margin-top: 0px;">這個段落的和上面段落的距離將爲20px</p> </section>
BFC (block formatting context) 塊級格式化上下文 =====》是爲了解決邊距塌陷(邊距重疊)問題。
BFC (block formatting context) 塊級格式化上下文code
即佈局規則
一、每一個元素的margin box的左邊,與包含塊border box 的左邊相接觸,即便浮動也如此
二、BFC區域不會與float box 重疊
三、BFC是一個隔離的獨立的容器,容器裏面的子元素的不會影響到外面的元素,反之亦然。
四、計算BFC高度的時候,浮動元素也參與計算。orm
一、overflow: 不爲visible 二、postion: absoluted, fixed 三、float 不爲none 四、根元素 五、display:inline-block\table-cell\table-caption\flex\inline-flex
一、自適應兩欄佈局htm
<section> <style> .left{ width: 100px; float:left; height: 100px; background-color: yellow; } .right{ height: 150px; background-color: red; overflow: hidden; } </style> <div class="left"></div> <div class="right"></div> </section>
二、清除內部浮動it
<section> <style> .par{ border:5px solid red; width:1000px; overflow: hidden;//生成BFC,把浮動元素的高度計算在內,變相地清除了內部浮動 } .child{ border: 5px solid blue; float: left; height:100px; width: 100px; } </style> <div class="par"> <div class="child"></div> <div class="child"></div> </div> </section>
三、防止邊距重疊(BFC中子元素邊距重疊)io
兩個div 中間取了最大值30爲重疊了,在p外面包裹一層容器,並觸發該容器生成一個 BFC。那麼兩個P便不屬於同一個BFC,就不會發生margin重疊了.
<section> <style> .wrap{ overflow: hidden; } .top{ height: 100px; margin-bottom: 40px; background-color: red; } .bottom{ height: 100px; margin-top: 30px; background-color:blue; } </style> <p class="top"></p> <div class="wrap"> <p class="bottom"></p> </div> </section>
總結:由於BFC內部的元素和外部的元素絕對不會互相影響,所以, 當BFC外部存在浮動時,它不該該影響BFC內部Box的佈局,BFC會經過變窄,而不與浮動有重疊。一樣的,當BFC內部有浮動時,爲了避免影響外部元素的佈局,BFC計算高度時會包括浮動的高度。避免margin重疊也是這樣的一個道理。table