1. 程式人生 > 其它 >css外邊距margin的塌陷問題

css外邊距margin的塌陷問題

子級元素的外邊距margin同時也會影響到父級元素,這就是css外邊距的塌陷問題。

舉個例子:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      text-decoration: none;
    }
    div {
      background-color: pink;
      height: 100px;
      width: 100px;
    }
    div.father {
      background-color: pink;
    }
    div.child {
      /* margin-top: 80px; */
      background-color: orange;
      height: 50px;
      width: 50px;
    }
  </style>
</head>
<body>
  <div class="father">
    <div class="child">child</div>
  </div>
 
</body>
</html>

顯示的結果為:

當在子級元素設定外邊距時,會同時影響到父級元素:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      text-decoration: none;
    }
    div {
      background-color: pink;
      height: 100px;
      width: 100px;
    }
    div.father {
      background-color: pink;
    }
    div.child {
      margin-top: 80px;
      background-color: orange;
      height: 50px;
      width: 50px;
    }
  </style>
</head>
<body>
  <div class="father">
    <div class="child">child</div>
  </div>
  
</body>
</html>

解決辦法:

  1. 父級元素控制內邊距即可。
  2. 父級元素新增overflow欄位取值為hidden
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      text-decoration: none;
    }
    div {
      background-color: pink;
      height: 100px;
      width: 100px;
    }
    div.father {
      padding-top: 25px;
      background-color: pink;
    }
    div.child {
      /* margin-top: 80px; */
      background-color: orange;
      height: 50px;
      width: 50px;
    }
  </style>
</head>
<body>
  <div class="father">
    <div class="child">child</div>
  </div>
  
</body>
</html>