一直都知道垂直方向上,可能會發生 margin
合併的問題,但後來發現是有前提的。css
前提:發生合併的2個元素,必須都是塊級元素。html
其中一個是內聯(
inline
或inline-block
)元素,就不會進行合併!app
因此,下面的組合,就不會發生合併spa
<input type="text" class="brother-input">
<div class="brother-div"></div>
複製代碼
.brother-input {
margin-bottom: 20px;
}
.brother-div {
width: 100px;
height: 50px;
background-color: salmon;
margin-top: 5px;
}
複製代碼
1,除了常見了相鄰兄弟元素,父子級元素以外,還有一個會發生合併的狀況。code
空塊級元素的 margin
合併:htm
<div class="wrapper">
<div class="inner"></div>
</div>
複製代碼
.wrapper {
overflow: hidden;
}
.inner {
margin: 10px 0;
}
複製代碼
此時,外層 div 的高度是 10px ,由於內層這個空的塊級元素的 margin-top
和 margin-bottom
發生了合併。input
2,即使不是相鄰的兄弟元素,也可能發生合併。string
<p>第1個p標籤</p>
<div></div>
<p>第2個p標籤</p>
複製代碼
p {
margin: 10px 0;
}
複製代碼
此時,2個 p 標籤之間的距離仍是 10px,由於中間的 div 是一個空的塊級元素,本來就是會發生合併的元素。class
而其實發生了3次合併:擴展
第1個 p 標籤的 margin-bottom
和 div 的 margin-top
發生了合併,
第2個 p 標籤的 margin-top
和 div 的 margin-bottom
發生了合併,
div 這個空的塊級元素, margin-top
和 margin-bottom
發生了合併。
解決:
border-top
或 border-bottom
padding-top
或 padding-bottom
height
,或是div元素內有內容讓其 height
不爲 0。對於 margin-top
合併( margin-bottom
同理)
overflow: hidden
border-top
padding-top
inline-block
元素進行分割。通常用僞元素 content: ''; display:inline-block;
進行處理。