【HTML/CSS】margin塌陷和合并问题

1 margin塌陷问题

1.1 示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>margin塌陷</title>
    <style>
        .parent{
     
     
            width: 200px;
            height: 200px;
            background-color: red;
            margin-left: 100px;
            margin-top: 100px;
        }
        .child{
     
     
            width: 100px;
            height: 100px;
            background-color: blue;
            margin-left: 50px;
            margin-top: 50px; /*子元素的margin-top无效?*/
        }
    </style>
</head>
<body>
    <div class="parent">
        <div class="child"></div>
    </div>
</body>
</html>

显示如下图所示,从图中可以看到子元素的margin-top没有显示出来,希望的是距离父盒子的顶部50px,但是现在和顶部重叠了,这就发生了margin塌陷。

造成的原因是:父子处于同一个BFC中,在同一个BFC中会出现垂直方向的margin重叠,margin重叠取最大值,即父元素的margin-top:100px。
在这里插入图片描述

1.2 margin塌陷的解决

可以触发BFC,改变父级的渲染规则。
在这里插入图片描述

        .parent{
    
    
            width: 200px;
            height: 200px;
            background-color: red;
            margin-left: 100px;
            margin-top: 100px;
            /*触发BFC*/
            /* position: absolute; */
            /* position: fixed; */
            overflow: hidden; /*推荐使用这种*/
            /* overflow: auto; */
            /* overflow: scroll; 会影响样式 */
            /* float: left; 会影响布局*/
            /* float: right; 会影响布局*/
            /* display: table-cell; */
        }

2 margin合并问题

2.1 示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>margin合并</title>
    <style>
        .one{
     
     
            background-color: red;
            height: 100px;
            width: 100px;
            margin-bottom: 100px;
        }
        .two{
     
     
            background-color: blue;
            height: 100px;
            width: 100px;
            margin-top: 50px;
        }
    </style>
</head>
<body>
    <div class="one"></div>
    <div class="two"></div>
</body>
</html>

如下图所示,两个兄弟块之间的margin合并了,显示的是较大值。
在这里插入图片描述

2.2 解决方法

  1. 为一个元素添加BFC,这种方法修改了HTML的结构,不好
    <div class="bfc">
      <div class="one"></div>
    </div>
    <div class="two"></div>
  1. 计算出合适的值,设置其中下面元素的margin-top或者上面元素的margin-bottom即可。

猜你喜欢

转载自blog.csdn.net/xd963625627/article/details/114283591
今日推荐