margin爲負值會導致元素產生偏移。
文檔流中的元素設置margin-bottom爲負值之後,會讓後面的元素向上流動填充margin的空間。
三個例子說明:
1.
<div style="height: 400px;margin-top: 50px;position: relative;border-bottom: 1px solid rgba(0,0,0,0);overflow: hidden;">
<div style="height: 200px;width: 100%;position: relative;background-color: rebeccapurple;margin: 0 0 -100px 0;">
</div>
<div style="height: 200px;background-color: peru">
</div>
</div>
第二個子元素向上流動,填充了margin的部分,但是因爲relative在z軸上的優先級更高,所以被覆蓋掉了一部分。
效果:
2.
<div style="height: 400px;margin-top: 50px;position: relative;border-bottom: 1px solid rgba(0,0,0,0);overflow: hidden;">
<div style="height: 200px;width: 100%;position: relative;background-color: rebeccapurple;margin: 0 0 -100px 0;">
</div>
<div style="height: 200px;background-color: peru;position: relative;">
</div>
</div>
兩個子元素都爲絕對定位,第二個子元素向上偏移,第二個子元素z軸上優先級更高,所以第一個子元素被覆蓋掉一部分。
效果:
3.
<div style="height: 400px;margin-top: 50px;position: relative;border-bottom: 1px solid rgba(0,0,0,0);overflow: hidden;">
<div style="height: 200px;width: 100%;background-color: rebeccapurple;margin: 0 0 -100px 0;">
</div>
<div style="height: 200px;background-color: peru">
</div>
</div>
兩個子元素都爲普通流,第二個元素向上流動,第一個元素被覆蓋掉一部分。
效果:
總結:普通流以及相對定位元素margin負值時,如果是margin-top爲負值,那麼盒子會向上流動。如果是margin-bottom爲負值,會讓後面的盒子向上流動。覆蓋規則爲:無定位或者定位方式相同時,在沒有設置z-index的情況下,向上流動的元素覆蓋前面的元素。定位方式不同時,有定位的元素覆蓋無定位的元素。
元素流動只能是向上流動,或者向左流動(內聯元素)。