问题:
当使用浮动调整样式时,浮动所在的区域将在页面中不占位置(在空中,不占实际位置),问题如下图,就会导致下面的元素块直接顶到顶端,无法实现上下分离的效果:
含义:清除浮动带来的影响
~影响:如果子元素浮动了,此时子元素不能撑开标准流的块级父元素
~原因: 子元素浮动后脱标 → 不占位置
~目的: 需要父元素有高度,从而不影响其他网页元素的布局
方法:
① 直接设置父元素高度
特点:
• 优点:简单粗暴,方便
• 缺点:有些布局中不能固定父元素高度。如:新闻列表、京东推荐模块
因为内容的高度是不确定的,容易不够或留白,实际中不会使用。
H5
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
样式
<style>
.father {
/* height: 400px; */ 不设置的话,就显示不出父元素,父元素的高度就会为0,不被子元素撑开
width: 400px;
background-color: pink;
}
.son {
float: left;
width: 100px;
height: 400px;
background-color: blue;
}
</style>
②额外标签法
• 操作:
- 在父元素内容的最后添加一个块级元素
- 给添加的块级元素设置 clear:both
• 缺点:会在页面中添加额外的标签,会让页面的HTML结构变得复杂
H5:
<div class="father">
<div class="son"></div>
<div class="abc"></div>
</div>
样式:
<style>
.father {
width: 400px;
background-color: pink;
}
.son {
float: left;
width: 100px;
height: 400px;
background-color: blue;
}
.abc{
clear: both;
}
</style>
③单伪元素清除法
H5中:
<div class="father clearfix"> 给他设置两个类名,同时生效
<div class="son"></div>
</div>
后续的类中有clearfix就可以
<div class="clearfix"></div>
<div class="clearfix"></div>
<div class="clearfix"></div>
<div class="clearfix"></div>
样式中:
<style>
.father {
width: 400px;
background-color: pink;
}
.son {
float: left;
width: 100px;
height: 400px;
background-color: blue;
}
.clearfix::after { /*clearfix类在这里设置*/
content: ''; /*是伪元素必加的,可以设置为空*/
display: block;
clear: both; /*相当于把上一个方法提取出来*/
/* 补充代码:在网页中看不到伪元素 */
height: 0;
visibility: hidden;
}
</style>
④双伪元素清除法
<!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>
.father {
width: 400px;
background-color: pink;
}
.son {
float: left;
width: 100px;
height: 400px;
background-color: blue;
}
.clearfix::before, /*可以解决盒子上部塌陷问题*/
.clearfix::after {
content: '';
display: table;
}
.clearfix::after {
clear: both;
}
</style>
</head>
<body>
<div class="father clearfix">
<div class="son"></div>
</div>
</body>
</html>
⑤ 给父元素设置overflow : hidden
H5
<div class="father">
<div class="son"></div>
</div>
样式:
<style>
.father {
width: 400px;
background-color: pink;
overflow: hidden; /*直接对父元素这个类操作*/
}
.son {
float: left;
width: 100px;
height: 400px;
background-color: blue;
}
</style>
⑥BFC盒子(了解)
<!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>
.father {
/* 1、把father盒子转换成BFC盒子,解决:清除浮动 */
/* float: left; */
/* display: inline-block; */
overflow: hidden;
width: 400px;
background-color: pink;
}
.son {
float: left;
width: 100px;
height: 400px;
background-color: blue;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>