高度塌陷问题及解决

什么情况下产生 (when

父盒子没有定义高度,但是子元素有高度,希望用子盒子撑起父盒子的高度,但是子盒子添加了浮动属性之后,父盒子高度为0

js 复制代码
<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

js 复制代码
<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: ''; }

js 复制代码
<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

  1. position:absolute;
  2. position: fixed;
  3. float:left;
  4. 具有overflow 且值不是 visible 的块元素,例如overflow:hidden;
  5. display: flow-root;
  6. 内联块 (元素具有 display: inline-block)
  7. display:flex
  8. display: inline-flex ;
相关推荐
茶茶只知道学习9 分钟前
通过鼠标移动来调整两个盒子的宽度(响应式)
前端·javascript·css
susu108301891128 分钟前
前端css样式覆盖
前端·css
东方翱翔1 小时前
CSS的三种基本选择器
前端·css
Fan_web1 小时前
JavaScript高级——闭包应用-自定义js模块
开发语言·前端·javascript·css·html
Java开发追求者2 小时前
在CSS中换行word-break: break-word和 word-break: break-all区别
前端·css·word
pink大呲花3 小时前
css鼠标常用样式
前端·css·计算机外设
天高任鸟飞dyz14 小时前
html加载页面
css·html·css3
Rverdoser19 小时前
unocss 一直热更新打印[vite] hot updated: /__uno.css
前端·css
MZZ骏马1 天前
svg与css关联
前端·css
GISer_Jing1 天前
CSS学习路线
前端·css·学习