我们经常把高度塌陷问题也叫做常见的几种清除浮动的方法
高度塌陷问题—父元素高度自适应,子元素float后,造成父元素高度为0,就叫做高度塌陷问题
给父元素一个高度
缺点:无法高度自适应
父元素{overflow:hidden;}
缺点: 父元素框之外的部分会被隐藏
在浮动的子元素的末尾,添加一个空div,并设置如下样式
div{clear:both; height:0;overflow:hidden;} 缺点:容易造成代码冗余
万能清除浮动法
父元素:after{content:””;display:block;clear:both;height:0;overflow:hidden;visibility:hidden;}
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>清除浮动的方法</title><style>*{margin: 0;padding: 0;}/* 方法一给父元素加一个高度 *//* .box{width: 600px;padding: 10px;background: gray;margin: 50px;height: 300px;} *//* 方法二 给父元素添加overflow-hidden 块级格式化上下文*//* .box{width: 600px;padding: 10px;background: gray;margin: 50px;overflow: hidden;} *//* 方法三末尾加一个空的div */.box{width: 600px;padding: 10px;background: gray;margin: 50px;}.childDiv{width: 200px;height: 300px;float: left;position: relative;left: 0;top: -50px;}.childDiv:nth-child(1){background: red;}.childDiv:nth-child(2){background: blue;}.childDiv:nth-child(3){background:pink;}/* 为了兼容ie: 6;的问题 *//* .clear{clear: both;height: 0;overflow: hidden;} *//* 方法四伪元素 */.box:after{content: "";display: block;clear: both;height: 0;overflow: hidden;/* 空间在 内容不显示 */visibility: hidden;}</style>
</head>
<body><div class="box"><div class="childDiv"></div><div class="childDiv"></div><div class="childDiv"></div><!-- <div class="clear"></div> --></div>
</body>
</html>
运行结果