清除浮动的方式有哪些?请说出各自的优点
问题:高度塌陷:当所有的子元素浮动的时候,且父元素没有设置高度,这时候父元素就会产生高度塌陷。
- 清除浮动方式1:给父元素单独定义高度; 优点:快速简单,代码少;缺点:无法进行响应式布局
<div class="parent">
<div class="children1"></div>
<div class="children2"></div>
</div>
.parent {
background-color: aqua;
/* 清除浮动方式1:给父元素单独定义高度
优点:快速简单,代码少 缺点:无法进行响应式布局 */
height: 300px;
}
.children1 {
width: 500px;
height: 300px;
background-color: bisque;
float: left;
}
.children2 {
width: 500px;
height: 300px;
background-color: rebeccapurple;
float: right;
}
- 清除浮动方式2:父级定义overflow:hidden;zoom:1(针对ie6 的兼容) 优点:简单快速、代码少,兼容性较高; 缺点:超出部分被隐藏,布局时要注意
<div class="parent">
<div class="children1"></div>
<div class="children2"></div>
</div>
.parent {
background-color: aqua;
/* 2.清除浮动方式2:父级定义overflow:hidden;zoom:1(针对ie6 的兼容) */
overflow: hidden;
}
.children1 {
width: 500px;
height: 300px;
background-color: bisque;
float: left;
}
.children2 {
width: 500px;
height: 300px;
background-color: rebeccapurple;
float: right;
}
- 清除浮动方式3:在浮动元素后面加一个空标签,clear:both;height:0;overflow:hidden; 优点:简单快速、代码少,兼容性较高; 缺点:增加空标签,不利于页面优化
<div class="parent">
<div class="children1"></div>
<div class="children2"></div>
<!-- 清除浮动方式3:在浮动元素后面加一个空标签,clear:both;height:0;overflow:hidden -->
<p style="clear: both; height: 0; overflow: hidden;"></p>
</div>
.parent {
background-color: aqua;
}
.children1 {
width: 500px;
height: 300px;
background-color: bisque;
float: left;
}
.children2 {
width: 500px;
height: 300px;
background-color: rebeccapurple;
float: right;
}
- 清除浮动方式4:父级定义overflow:auto; 优点:简单,代码少,兼容性好; 缺点:内部宽高超过父级div时,会出现滚动条;
<div class="parent">
<div class="children1"></div>
<div class="children2"></div>
</div>
.parent {
background-color: aqua;
/* 清除浮动方式4:父级定义overflow:auto */
/* overflow: auto; */
}
.children1 {
width: 500px;
height: 300px;
background-color: bisque;
float: left;
}
.children2 {
width: 500px;
height: 300px;
background-color: rebeccapurple;
float: right;
}
5.清除浮动方式5:万能清除法:给塌陷的元素添加伪对象 .parent::after { content: ""; clear: both; display: block; height: 0; overflow: hidden; visibility: hidden; } 优点:写法固定,兼容性高; 缺点:代码多
<div class="parent">
<div class="children1"></div>
<div class="children2"></div>
</div>
.parent {
background-color: aqua;
}
/* 清除浮动方式5:万能清除法:给塌陷的元素添加伪对象 */
.parent::after {
content: "";
clear: both;
display: block;
height: 0;
overflow: hidden;
visibility: hidden;
}
.children1 {
width: 500px;
height: 300px;
background-color: bisque;
float: left;
}
.children2 {
width: 500px;
height: 300px;
background-color: rebeccapurple;
float: right;
}