清除浮动的简介
主要含义:清除浮动带来的影响
原因: 子元素浮动后脱标→不占位置。
目的: 需要设置高度,从而不影响其他网页元素的布局。
清除浮动的方法
方法一:直接设置高度
优缺点:
优点:简单粗暴,方便。
缺点:有些布局中不能固定父元素高度。如:新闻列表、京东推荐模块。
<style>
.father {
width: 400px;
height:500px;
background-color: red;
}
.son {
float: left;
width: 100px;
height: 400px;
background-color: green;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
方法2:额外标签法
1.在父元素内容的最后添加一个块级元素
2. 给添加的块级元素设置 clear:both
特点:
缺点:会在页面中添加额外的标签,会让页面的HTML结构变得复杂
<style>
.father {
width: 400px;
background-color: red;
}
.son {
float: left;
width: 100px;
height: 400px;
background-color: green;
}
.aaa {
clear: both;
}
</style>
<body>
<div class="father">
<div class="son"></div>
<div class="aaa"></div>
</div>
</body>
方法3:单伪元素清除法
操作:用伪元素替代了额外标签
(1)基本写法:
<style>
.father {
width: 400px;
background-color: red;
}
.son {
float: left;
width: 100px;
height: 400px;
background-color: green;
}
.father::after {
content: '';
display: block;
clear: both;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
(2)补充写法:
<style>
.clearfix::after {
content: '';
display: block;
clear: both;
/* 补充代码:在网页中看不到伪元素 */
height: 0;
visibility: hidden;
}
</style>
<body>
<div class="father clearfix">
<div class="son"></div>
</div>
方法4:双伪元素清除法
特点:
优点:项目中使用,直接给标签加类即可清除浮动。
操作:
<style>
.clearfix::before,
.clearfix::after{
content: '';
display: table;
}
.clearfix::after {
clear: both;
}
</style>
<body>
<div class="father clearfix">
<div class="son"></div>
</div>
</body>
after可以用来解决浮动,before可以用来解决盒子上部的塌陷现象。
方法5:给父元素设置overflow : hidden
直接给父元素设置overflow : hidden
<style>
.father {
width: 400px;
height:500px;
background-color: red;
overflow: hidden;
}
.son {
float: left;
width: 100px;
height: 400px;
background-color: green;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
小编刚开始写,如有错误可在评论区留言及时更正哦~
欢迎大家留言!!!