盒模型 bug 与触发 bfc

 一、margin合并

  css经典bug  两个块级元素 分别设置 margin-bottom 和 margin-top 并不能达到预期效果

  <style>
    .up{
      width: 200px;
      height: 50px;
      background: blue;
      margin-bottom: 50px;
    }
    .down{
      width: 200px;
      height: 50px;
      background: pink;
      margin-top: 50px;
    }
  </style>
</head>
<body>
  <div class="up"></div>
  <div class="down"></div>
</body>

上面代码的最终效果   中间的距离 并不是margin-top + margin-bottom    而是      两者 中取大的那个 的值      就像 合并到了一

解决方法

  给 up 和 down 都加上父级  并给父级设置  overflow:hidden

  

margin塌陷

  wrapper 包裹 box   wrapper的margin-top和box的margin-top 取最大值 且 box 紧紧贴纸 wrapper的人上边  并不是 box相对wrapper 取 margin-top

  <style>
    .wrapper{
      width: 200px;
      height: 200px;
      background: rgb(228, 143, 143);
    }
    .box{
      width: 50px;
      height: 50px;
      margin-top: 20px;
      border: 1px solid blue;
    }
  </style>
</head>
<body>
  <div class="wrapper">
    <div class="box"></div>
  </div>
</body>

  

解决方法 

    1.利用給父级添加 border 来触发  bfc效果 

      类似子集看不见父级的边界  添加一个  border 来解决  但改变 父级的样式 (舍去)

    2.利用給父级添加 overflow 属性触发 bfc 

bfc

  block format context  块级格式化上下文

 触发bfc 的方法  

    postion: absolute;

    display: inline-block;

    overflow: hidden;

    float:left/right

原文地址:https://www.cnblogs.com/96weibin/p/7875501.html