解决外边距溢出的问题和解决浮动塌陷问题

本文探讨了几个CSS解决方案,包括使用padding调整元素位置、利用overflow属性创建BFC防止外边距折叠、添加伪元素以及考虑使用表格布局来优化元素排列。同时,展示了如何通过clearfix类解决浮动元素导致的父元素高度不正确问题。
摘要由CSDN通过智能技术生成

1、使用padding改变:padding:10px;
相对应的父级高度也要改变
2、父元素使用overflow属性的hidden、auto、scroll其中一个,可以触发父级的bfc,从而解决外边距溢出的问题
3、给父元素增加上边框
4、在HTML中添加table
5、在css中添加伪元素,添加到父元素中

<!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>
       .box{
           width: 300px;
           height: 300px;
           background-color: green;
           /* overflow: hidden; 2.给父元素添加overflow:hidle;*/
           /* border-top: 1px solid green; 1.给父元素增加上边框*/
       }
       .one{
           width: 150px;
           height: 150px;
           margin-top: 100px;
           background-color: red;
       }
       .m::before{
           content: '';
           display: table;
       }
       /* 4.在css中添加伪元素,添加到父元素中,  .m::before{
           content: '';
           display: table;
       } */
    </style>
</head>
<body>
    <div class="box m">
        <!-- <table></table> 3.在HTML中添加table-->
        <div class="one"></div>
    </div>
</body>
</html>
<!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>
        .box{
            width: 500px;
            border: 2px solid red;     
        }
        .one{
            width: 200px;
            height: 200px;
            background-color: pink;
            float: left;
        }
        .two{
            width: 200px;
            height: 200px;
            background-color: green;
            float: left;
        }
        /* .clearfix{
            clear: both;
        } 第一种方法*/
        .clearfix::after{
            content: '';
            /* display: block; */
            display: table;
            clear: both;
        }/*第二种方法*/
    </style>
</head>
<body>
    <div class="box clearfix">
        <div class="one"></div>
        <div class="two"></div>
        <!-- <div class="clearfix"></div>第一种方法 -->
    </div>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值