高度塌陷问题及解决

什么情况下产生 (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 ;
相关推荐
哈里谢顿3 小时前
CSS 入门完全指南:从零构建你的第一个样式表
css
. . . . .3 小时前
CSS 编写与管理范式 - Tailwind和CSS-in-JS
css
RFCEO21 小时前
前端编程 课程十六、:CSS 盒子模型
css·前端基础课程·css盒子模型·css盒子模型的组成·精准控制元素的大小和位置·css布局的基石·内边距(padding)
夏幻灵1 天前
CSS三大特性:层叠、继承与优先级解析
前端·css
会编程的土豆2 天前
新手前端小细节
前端·css·html·项目
珹洺2 天前
Bootstrap-HTML(二)深入探索容器,网格系统和排版
前端·css·bootstrap·html·dubbo
BillKu2 天前
VS Code HTML CSS Support 插件详解
前端·css·html
1024小神2 天前
用css的clip-path裁剪不规则形状的图片展示
前端·css
GGGG寄了2 天前
CSS——文字控制属性
前端·javascript·css·html
HWL56792 天前
在网页中实现WebM格式视频自动循环播放
前端·css·html·excel·音视频