浮动的框可以向左或向右移动,直到它的外边缘碰到包含框或另一个浮动框的边框为止。
由于浮动框不在文档的普通流中,所以文档的普通流中的块框表现得就像浮动框不存在一样。
——文章参考w3school
1、探讨为什么要清除浮动?
清除浮动不是取消浮动框的浮动状态,而是因为浮动元素脱离文档流导致的高度塌陷等问题需要清楚浮动来解决,看下面的例子
-
例子中的 html
<div class="out"> <div class="float"></div> </div> -
先看个不浮动的情况
.out { width: 400px; background-color: silver; } .float { width: 100px; height: 200px; background-color: red; } -
当子盒子浮动的时候出现的情况
.out { width: 400px; background-color: silver; } .float { float: right; width: 100px; height: 200px; background-color: red; }我们会发现当父盒子未设置高度控制,需要靠子盒子撑起高度,即随内容的高度增加而增加的,这种情况下,如果所有子盒子都是浮动的,就会出现父盒子高度塌陷,就像上图;或者浮动的盒子的高度比正常文档流盒子撑起的父盒子高度都高的情况下,浮动盒子就会溢出父盒子之外,清除浮动就是要解决这类情况。
2、如何清除浮动?
方法1:添加标签
<div class="out">
<div class="float"></div>
<!-- 新增 clear 这个标签在下方 -->
<div class="clear"></div>
</div>
.out {
width: 400px;
background-color: silver;
}
.float {
float: right;
width: 100px;
height: 200px;
background-color: red;
}
.clear {
clear: both; // 核心代码
}
效果:
知识点补充:
clear 属性:有四个可设置的值——> left、right、both、none
分别表示清除左边、右边、所有、不清除四种情况,元素设置该属性后相当于,虽然浮动元素不在文档流里了,但是设置了该属性就依然当他们存在,想念他们,给他们留空间。
方法2:父级添加overflow属性,或者设置高度
<div class="out">
<div class="float"></div>
</div>
.out {
width: 400px;
overflow: hidden; // 核心代码 设置为 auto 也行
background-color: silver;
}
.float {
float: right;
width: 100px;
height: 200px;
background-color: red;
}
效果:
方法3:建立伪类选择器清除浮动【推荐】
<div class="out">
<div class="float"></div>
</div>
.out {
width: 400px;
background-color: silver;
}
.float {
float: right;
width: 100px;
height: 200px;
background-color: red;
}
.out::after {
/* 设置添加子元素的内容是空 */
content: '';
/* 设置添加子元素为块级元素 */
display: block;
/* 设置添加的子元素的高度0 */
height: 0;
/* 设置添加子元素看不见 */
visibility: hidden;
/* 设置clear:both */
clear: both;
}
效果: