<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            *{margin:0px; padding:0px;}
            .box1{
                width: 300px;
                height: 300px;
                background-color: red
            }
            .box2{
                width: 200px;
                height: 200px;
                background-color: yellow;
                margin-top: 100px;
            }
    
        </style>
    </head>
    <body>
        
        
        <div class="box1 ">
            
            <div class="box2"></div>
        </div>
        
    </body>
</html>

当把子元素margin-top:100 时,其父元素会跟着一样改变

HTML-完美解决父子元素的外边距重叠和高度塌陷问题

解决方法

用css解决

.clearfix:before,
            .clearfix:after{
                content: "";
                display: table;
                clear: both;
            }
            
            .clearfix{
                zoom: 1;
            }

形成以下完全代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            *{margin:0px; padding:0px;}
            .box1{
                width: 300px;
                height: 300px;
                background-color: red
            }
            .box2{
                width: 200px;
                height: 200px;
                background-color: yellow;
                margin-top: 100px;
            }
            .clearfix:before,
            .clearfix:after{
                content: "";
                display: table;
                clear: both;
            }
            
            .clearfix{
                zoom: 1;
            }
    
        </style>
    </head>
    <body>
        
        
        <div class="box1  clearfix">
            
            <div class="box2"></div>
        </div>
        
    </body>
</html>

 

运行后变成

HTML-完美解决父子元素的外边距重叠和高度塌陷问题

相关文章:

  • 2021-08-25
  • 2022-12-23
  • 2021-11-08
  • 2022-12-23
  • 2022-12-23
  • 2022-01-02
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-22
  • 2021-12-27
  • 2021-12-31
  • 2022-12-23
  • 2021-05-01
  • 2021-06-06
  • 2021-12-07
相关资源
相似解决方案