css外邊距合並問題(外邊距塌陷)


1.父子元素之間的外邊距margin合並問題(外邊距塌陷)

<!-- 結構 -->
<div class="box">
    <div class="b1"></div>
</div>
<!-- 樣式 -->
.box {
            width: 800px;
            height: 500px;
            background-color: orange;
        }

        .b1 {
            margin-top: 20px;
            width: 200px;
            height: 200px;
            background-color: purple;
        }

 

我們想要的效果是這樣的

但實際是這樣的

解決方法:

  父元素添加代碼段:
              /*border: 1px solid transparent; !*方法1*!*/
            /*float: left; !*方法2*!*/
            /*position: absolute; !*方法3*!*/
            /*padding: 1px; !*方法4*!*/
            /*display: inline-block; !*方法5*!*/
            /*overflow: hidden; !*方法6*!*/
            /*overflow: auto; !*方法7*!*/            

 

2.兄弟元素之間的外邊距合並問題

<!--結構-->
<div class="box1">
    <div class="b2"></div>
    <div class="b3"></div>
</div>

<!--樣式-->
.b2,
.b3 {
width: 100px;
height: 100px;
border: 1px solid #ccc;
}

.b2 { background-color: pink; margin-bottom: 20px; } /* b2 margin-bottom 20px; b3 margin-top 30px ;本應該b2 和 b3 間隔50px */ /* 實際 只有 30px 因為外邊距margin發生了合並 */ .b3 { margin-top: 30px; background-color: green; }

我們想要的效果:粉色 和 綠色間隔為50px

但實際是這樣的:間隔只有 30px 因為margin發生了合並 合並后就只剩margin值較大的部分

解決方法:

<!--增加左浮動 或 轉換為行內塊-->
 /*float: left; !* 1.設置左浮動 解決外邊距margin 合並問題呢*! */
    /*display: inline-block; !*2.轉換為行內塊 解決外邊距margin 合並問題*!*/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM