css margin塌陷

195 阅读1分钟

场景复现

1、demo

<!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>
    * {
      padding: 0;
      margin: 0;
    }
    .box1 {
      width: 200px;
      height: 200px;
      background-color: blue;
    }
    .box2 {
      width: 100px;
      height: 100px;
      background-color: green;
    }
  </style>
</head>
<body>
  <div class="box1">
    <div class="box2"></div>
  </div>
</body>
</html>

页面效果

image.png

2、给box2元素加一行样式

margin-top: 50px;

页面效果,并未如预期一样作用在box2元素里,而是直接作用在了box1里,这就是css塌陷

image.png

解决方案

塌陷触发条件:两个盒子的垂直外边距完全接触时会触发css margin塌陷

a、为父元素设置border,添加border后父子元素就不是真正意义上的完全接触;

b、为父元素设定padding-top: 1px;

c、为父元素添加overflow: hidden;

d、为父元素添加position: fixed;

e、为父元素添加display: table;

image.png