什么情况下产生 (when
父盒子没有定义高度,但是子元素有高度,希望用子盒子撑起父盒子的高度,但是子盒子添加了浮动属性之后,父盒子高度为0
 
<template><div class="father"><div class="son">rr</div></div>
</template><script setup></script>
<style lang="scss" scoped>.father {--left-width: 200px;border: 1px solid blue;.son {float: left;width: 60px;height: 200px;background-color: red;}}
</style>为什么高度塌陷了 (why
子盒子添加浮动属性,脱离了文档流,不再占据位置,所以不能撑起父盒子,所以父盒子高度塌陷了
怎么解决 (how

法1:给父盒子添加固定高度
缺点:不能自适应高度,灵活性不好
法2:子盒子结尾添加空div并clear:both
left:清除左侧浮动元素对当前元素的影响
 right:清除右侧浮动元素对当前元素的影响
 both:清除两侧中最大影响的那侧
 clear: both
<template><div class="father"><div class="son">rr</div><!-- 添加空的div,并 clear: both--><div style="clear: both"></div> </div>
</template><script setup></script>
<style lang="scss" scoped>.father {--left-width: 200px;border: 1px solid blue;.son {float: left;width: 60px;height: 200px;background-color: red;}}
</style>法3:给父元素设置伪元,并设置清除浮动的样式
给塌陷的父盒子添加
 ::after { display: block; clear: both; content: ''; }
<template><div class="father"><div class="son">rr</div></div>
</template><script setup></script>
<style lang="scss" scoped>.father {--left-width: 200px;border: 1px solid blue;&::after {display: block;clear: both;content: '';}.son {float: left;width: 60px;height: 200px;background-color: red;}}
</style>法4:添加BFC
- position:absolute;
- position: fixed;
- float:left;
- 具有overflow 且值不是 visible 的块元素,例如overflow:hidden;
- display: flow-root;
- 内联块 (元素具有 display: inline-block)
- display:flex
- display: inline-flex ;