浮动和清除浮动

当非IE浏览器中,子元素浮动后,父元素可能会出现高度塌陷,内容溢出影响布局。这种现象称为浮动溢出。文章介绍了四种解决方法:1) 使用`overflow:hidden`;2) 父元素设定高度;3) 添加清浮动空div;4) 利用`::after`伪元素。这些方法能有效防止高度塌陷并保持页面布局的稳定性。
摘要由CSDN通过智能技术生成

浮动: 非IE浏览器下,容器不设高度 子元素浮动时,容器高度不能被内容撑开。 此时,内容会溢出到容器外面而影响布局。这种现象被称为浮动(溢出)。
浮动元素脱离文档流,不占据空间,引起“高度塌陷”

<style>
.father{width: 400px;background-color: yellow;border: 1px solid black;}
.son{width: 100px;height: 100px;background-color: red;float: left;}
</style>
<div class="father">
    <div class="son"></div>
</div>
<p>123</p>

在这里插入图片描述

清除浮动的方法:
1、包含浮动元素的父级标签添加overflow:hidden或者overflow:auto

<style>
.father{
    width: 400px;background-color: yellow;border: 1px solid black;
    overflow: hidden; /* BFC */ 
}
.son{width: 100px;height: 100px;background-color: red;float: left;}
</style>
<div class="father">
    <div class="son"></div>
</div>
<p>123</p>

2、给父级div定义height属性:height: 100px;

<style>
.father{
	width: 400px;background-color: yellow;border: 1px solid black;
	height: 100px;
}
.son{width: 100px;height: 100px;background-color: red;float: left;}
</style>
<div class="father">
    <div class="son"></div>
</div>
<p>123</p>

3、最后一个浮动元素之后添加一个空的div标签,并添加clear:both样式

<style>
.father{width: 400px;background-color: yellow;border: 1px solid black;}
.son{width: 100px;height: 100px;background-color: red;float: left;}
.clear{clear: both;}
</style>
<div class="father">
    <div class="son"></div>
    <div class="clear"></div>
</div>
<p>123</p>

4、使用 ::after 伪元素:.clearFix::afte

<style>
.father{width: 400px;background-color: yellow;border: 1px solid black;}
.son{width: 100px;height: 100px;background-color: red;float: left;}
.clearFix::after{
    content: "";
    clear: both;
    display: block;
}
</style>
<div class="father clearFix">
    <div class="son"></div>
</div>
<p>123</p>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值