css边界塌陷和边距重叠问题

2,199 阅读1分钟

两个相邻子元素边距发生重叠:

<div class="up"></div>
<div class="down"></div>

.up{
             width:200px;
             height:200px;
             background-color: red;
             margin-bottom: 30px;
  }
.down{
            width:200px;
            height:200px;
            background-color: orange;
            margin-top:20px
}

父子元素边距重叠和父元素塌陷:

<!DOCTYPE html>
<html lang="en" style="padding: 0px">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            pading: 0;
        }
        .container{
            width:300px;
            height:300px;
            background-color: pink;
            margin-top:20px
        }
        .child{
           width:100px;
            height:100px;
            background-color: orange;
            margin-top: 30px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="child"></div>
</div>
</body>
</html>

同时第二个父子元素的重叠也是一个父元素塌陷的问题:

解决这种元素塌陷的问题方式有:

方式1:

给父元素添加一个border:

 .container{
            border:1px solid red;
        }

方式2:给父元素一个padding:

 .container{
            padding:1px;
        }

方式3:

给父元素添加overflow:hidden属性。

 .container{
            overflow:hidden;
        }

方式4:

给子元素设置display:inline-block属性

 .child{
     display:inline-block;
        }

方式5:使子元素脱离标准流

 .child{
         display:absolute;
        }
  或者:
.child{
     float:left;
      }