浮动引起的高度塌陷问题

正常页面布局

 <style>
        *{
            margin:0;
            padding: 0;
        }
        .content{
            width:400px;
            border:1px solid #000;
            
        }
        .box{
            width:200px;
            height:200px;
            background: greenyellow;
            
        }
    </style>

<body>
    <div class="content">
        <div class="box"></div>
    </div>
    <p>基苦阿斯蒂芬</p>
</body>

在这里插入图片描述
当给类名为.box的盒子加上浮动后

<style>
        *{
            margin:0;
            padding: 0;
        }
        .content{
            width:400px;
            border:1px solid #000;
            
        }
        .box{
            width:200px;
            height:200px;
            background: greenyellow;
            float: left;
            
        }
    </style>

在这里插入图片描述
可以看到页面布局已经乱了,因为元素设置浮动后会脱离文档流

解决方案

1 利用BFC(给父元素加上overflow:hidden)

**缺点:父元素溢出的元素会隐藏,可能会影响页面显示 **

 .content{
            width:400px;
            border:1px solid #000;
            overflow: hidden;
            
        }
2 加空div

要点:
1.加上一个空的块级元素
2.对块级元素进行清除浮动, 省事方法,不管理是左浮还是右浮,直接全清(clear:both)

    <style>
        *{
            margin:0;
            padding: 0;
        }
        .content{
            width:400px;
            border:1px solid #000;
            /* overflow: hidden; */
            
        }
        .box{
            width:200px;
            height:200px;
            background: greenyellow;
            float: left;
            
        }
        .clear{
            clear: both;
        }
    </style>
    
<body>
    <div class="content">
        <div class="box"></div>
        <div class="clear"></div>
    </div>
    <p>基苦阿斯蒂芬</p>
</body>
3 利用伪元素

要点:
1 其实和加空div的原理是一致的,唯一要记住的就是把伪元素转为块级元素(display:block),否则会没有效果
2 还有伪元素的属性不要忘记加上(content:‘’)

<style>
        *{
            margin:0;
            padding: 0;
        }
        .content{
            width:400px;
            border:1px solid #000;
            /* overflow: hidden; */
            
        }
        .content::after{
            content: '';
            display: block; // 必须要转换为块元素
            clear: both;
        }
        .box{
            width:200px;
            height:200px;
            background: greenyellow;
            float: left;
            
        }
        /* .clear{
            clear: both;
        } */
    </style>

<body>
    <div class="content">
        <div class="box"></div>
        <!-- <div class="clear"></div> -->
    </div>
    <p>基苦阿斯蒂芬</p>
</body>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值