【CSS面试题】高度塌陷问题及解决

什么情况下产生 (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: ''; }

其实它和上一条的原理相同,注意这个::after是添加在这个元素的里面的最后,而不是这个元素的外边在这里插入图片描述

<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 ;
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值