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

时间:2019-10-25 16:08:23   收藏:0   阅读:246
<!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 时,其父元素会跟着一样改变

技术分享图片

解决方法

用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>

 

运行后变成

技术分享图片

原文:https://www.cnblogs.com/hack-ing/p/11738316.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!