CSS样式-外边距塌陷

当子级设置margin-top时,父级也会随着子级设置的margin-top下沉

<!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 type="text/css">
        #father {
            width: 400px;
            height: 400px;
            background-color: #f00;
        }
        #son {
            width: 200px;
            height: 200px;
            background-color: #0f0;
            margin-left: 50px;
            margin-top: 50px;
        }
    </style>
</head>
<body>
    <div id="father">
        <div id="son"></div>
    </div>
</body>
</html>
 
解决方法一,给父级设置padding-top,并且如果保持高度不变,height需要减去50px:
  
   #father {
            width: 400px;
            height: 350px;
            background-color: #f00;
    padding-top:50px;
        }
解决方法二,给父级div放一个padding进去,同时调整父级的height,以及子级的margin-top
height + padding-top = 原来的height;
padding-top + margin-top = 父级与子级之间需要的距离;
  
  #father {
            width: 400px;
            height: 399px;
            background-color: #f00;
    padding-top:1px;
        }
  
   #son {
            width: 200px;
            height: 200px;
            background-color: #0f0;
            margin-top: 49px;
        }
解决方法三,给父级div放一个border进去,并且将border的颜色设置成与父级div的背景颜色相同,起到迷惑作用
  
  #father {
            width: 400px;
            height: 399px;
            background-color: #f00;
      border-top: 1px solid #f00;
        }
  
  #son {
            width: 200px;
            height: 200px;
            background-color: #0f0;
            margin-top: 49px;
  }
解决方法四,给父级div增加overflow: hidden
  
  #father {
            width: 400px;
            height: 400px;
            background-color: #f00;
      overflow: hidden;
        }
  
  #son {
            width: 200px;
            height: 200px;
            background-color: #0f0;
            margin-top: 50px;
  }
posted @ 2021-02-25 23:54  #Friday  阅读(78)  评论(0)    收藏  举报