什么是margin塌陷

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <link rel="stylesheet" href="../css/index.css" type="text/css">
  6. </head>
  7. <body>
  8. <div class="wrapper">
  9. <div class="content"></div>
  10. </div>
  11. </body>
  12. </html>
.wrapper{
    width: 200px;
    height: 200px;
    background-color: orange;
    margin-top: 100px;
    margin-left: 100px;
}


.content{
    width: 100px;
    height: 100px;
    background-color: green;
}

显示效果
image.png
两个盒子,我们给父级设置margin发现正常,接下来我们给绿色盒子设置margin来看看情况

.content{
    margin-top: 50px;
    margin-left: 50px;
    width: 100px;
    height: 100px;
    background-color: green;
}

image.png
我们发现margin-left是正常的,但是margin-top并没有生效,绿色方块并没有跟橙色方块有上边距。这是为什么?我们再试试将margin-top的值改大。

.content{
    margin-top: 150px;
    margin-left: 50px;
    width: 100px;
    height: 100px;
    background-color: green;
}

image.png
我们发现绿色方块居然带着橙色方块一起往下移动了。这就是mragin塌陷的问题。垂直方向的margin他们是共用的。

BFC解决办法:

BFC叫做块级格式化上下文。每个盒子都有特定的语法规则, BFC能改变这个规则。如何触发BFC?
1 position : absolute
2 display : inline-block
3 float :left/right
4 overflow : hiddent

这4个办法都能够解决margin塌陷的问题,具体是用的时候,根据实际情况选择。