高度塌陷问题及解决

什么情况下产生 (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 ;
相关推荐
alexander0684 小时前
CSS 类选择器组合
前端·css
HexCIer17 小时前
面向未来的原子化 CSS:UnoCSS 核心架构分析与 Tailwind CSS 现状
前端·css·vite
用户059540174461 天前
把大模型记忆回归测试从手工检查换成 Playwright+VCR,误判率从 40% 降到 0
前端·css
breeze jiang1 天前
从零搭建浏览器端 AI 原型:React、WebGPU 与 Tailwind CSS 的一次实践
css·人工智能·react.js
不好听6131 天前
Tailwind CSS 原子化 CSS 完全入门:为什么现代前端开发都在用?
前端·css
奇牙coding2 天前
gpt-5.6-sol 接入指南:reasoning_effort 参数配置、推理链验证与常见报错排查
前端·css·gpt·ai
lastknight3 天前
CSS @layer
前端·css
用户059540174463 天前
用 Pytest 接管大模型记忆存储测试,状态一致性问题减少 90%
前端·css
甜味弥漫5 天前
一文搞懂 Flex 弹性布局:为什么它成为现代 CSS 布局的首选?
css
用户059540174465 天前
AI记忆存储一致性踩坑实录:每天手工回归200条对话,直到我用pytest+Redis搭建自动化验证
前端·css