1. html元素高度塌陷的几种情况
- 子元素浮动(float)
- 绝对定位(absolute)
- 固定定位(fixed)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
.collapse {
border: 3px dashed red;
margin-bottom: 50px;
}
.child {
width: 50px;
height: 50px;
background-color: blue;
}
.float {
float: left;
border: 1px solid;
}
.absolute {
position: absolute;
}
.fixed {
position: fixed;
}
</style>
</head>
<body>
<div class="collapse">
collapse1
<div class="child float">
</div>
</div>
<div class="collapse">
collapse2
<div class="child absolute">
</div>
</div>
<div class="collapse">
collapse3
<div class="child fixed">
</div>
</div>
</body>
</html>
2. 高度塌陷的解决方案
2.1 清除浮动
/* 清除浮动 */
.clearfix::after{
content: "";
display:block;
clear: both;
height: 0;
visibility: hidden;
}
.clearfix {
/* 触发 hasLayout */
zoom: 1;
}
2.2 设置父元素的高度
.parent {
height:100px;
}
此方法父元素无法自适应子元素的高度。