當兩個盒子在垂直方向上設置margin值時,會出現一個有趣的塌陷現象。
①垂直並列
首先設置兩個DIV,併爲其制定寬高
-
1 /*HTML部分*/ 2 <body> 3 <div class="box1">box1</div> 4 <div class="box2">box2</div> 5 </body> 6 /*CSS部分*/ 7 <style> 8 *{ 9 margin: 0; 10 padding: 0; 11 } 12 .box1{ 13 width: 200px; 14 height: 200px; 15 background: yellowgreen; 16 } 17 .box2{ 18 width: 200px; 19 height: 200px; background: gray; 20 } 21 </style>
對box1我們爲其設置margin-bottom:50px;
對box2我們爲其設置margin-top: 40px;
-
1 <style> 2 *{ 3 margin:0; 4 padding:0; 5 } 6 .box1{ 7 width:200px; 8 height:200px; 9 background: yellowgreen; 10 margin-bottom: 50px; 11 } 12 .box2{ 13 width:200px; 14 height:200px; 15 background: gray; 16 margin-top: 40px; 17 } 18 </style>
我們肯定會很理所當然的認定這兩個盒子之間的距離爲90px,事實上並非如此.
如下圖所示:
兩盒子之間的距離僅是50px,也就是說兩盒子之間的margin出現了重疊部分,故而我們可以得出:垂直之間塌陷的原則是以兩盒子最大的外邊距爲準。
②嵌套關係(父級元素塌陷)
-
1 /*CSS部分*/ 2 <style> 3 .box1{ 4 width:400px; 5 height:400px; 6 background: pink; 7 } 8 .box2{ 9 width:200px; 10 height:200px; 11 background: lightblue; 12 } 13 </style> 14 /*HTML部分*/ 15 <body> 16 <divclass="box1"> 17 <divclass="box2"></div> 18 </div> 19 </body>
如圖示
當爲子盒子添加margin-top:10px;時會發生如下情況:
子盒子和父盒子之間並沒出現期望的10px間隙而是父盒子與子盒子一起與頁面頂端產生了10px間隙(即父級盒子往下塌陷了10px)。
解決方法:
(1)爲父盒子設置border,爲外層添加border後父子盒子就不是真正意義上的貼合 (可以設置成透明:border:1px solid transparent)。
(2)爲父盒子添加overflow:hidden;
(3)爲父盒子設定padding值;
(4)爲父盒子添加position:fixed;
(5)爲父盒子添加 display:table;
(6)利用僞元素給子元素的前面添加一個空元素
.son:before{ content:""; overflow:hidden; }