margin塌陷和margin合並問題及解決方案


margin塌陷

先舉個例子

<style>
        body{
            background-color:#000;
        }
     .wrapper{
         width:200px;
         height:200px;
         background-color:red;
         margin-top:100px;
     }
     .box{
        width:50px;
         height:50px;
         background-color:#eee;
         opacity:0.8;
     }
    </style>
</head>
<body >
        <div class="wrapper">
            <div class="box"></div>
        </div>
</body>

距離上邊100px;

現在給里面的小方塊設置margin-top:100px;發現兩個方塊位置沒動;

而當給里面的小方塊設置margin-top:150px;小方塊帶着大方塊往下移動了50px

原理:父子嵌套元素在垂直方向的margin,父子元素是結合在一起的,他們兩個的margi會取其中最大的值.

正常情況下,父級元素應該相對瀏覽器進行定位,子級相對父級定位.

但由於margin的塌陷,父級相對瀏覽器定位.而子級沒有相對父級定位,子級相對父級,就像坍塌了一樣.

 

margin塌陷解決方法

1.給父級設置邊框或內邊距(不建議使用)

 .wrapper{
         width:200px;
         height:200px;
         background-color:red;
         margin-top:100px;
         border-top:1px solid black;
     }

 

2.觸發bfc(塊級格式上下文),改變父級的渲染規則

方法:

改變父級的渲染規則有以下四種方法,給父級盒子添加

(1)position:absolute/fixed

(2)display:inline-block;

(3)float:left/right

(4)overflow:hidden

這四種方法都能觸發bfc,但是使用的時候都會帶來不同的麻煩,具體使用中還需根據具體情況選擇沒有影響的來解決margin塌陷

 

 margin合並

原理:兩個兄弟結構的元素在垂直方向上的margin是合並的

html

1  <div class="box1"></div>
2  <div class="box2"></div>

 

css

        *{
            margin: 0;
            padding: 0;
        }
        body {
            background-color: #000;
        }
        .box1 {
            height: 30px;
            margin-bottom: 100px;
            background-color: red;
        }
        .box2 {
            height: 30px;
            margin-top: 100px;
            background-color: aqua;
        }

margin合並問題也可以用bfc解決,

1.給box2加上一層父級元素並加上overflow:hidden;

  <div class="box1"></div>
   <div class="wrapper">
        <div class="box2"></div>
  </div>
.wrapper{
            overflow:hidden;
        }

2.給兩個都加一層父級再加bfc

    <div class="wrapper">
        <div class="box1"></div>
    </div>
    <div class="wrapper">
        <div class="box2"></div>
    </div>

但是這兩種方法都改變了HTML結構,在開發中是不能采用的

所以在實際應用時,在margin合並這個問題上,我們一般不用bfc,而是通過只設置上面的元素的margin-bottom來解決距離的問題

 


免責聲明!

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



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