【CSS面试题】外边距折叠的原因和解决

本文介绍了CSS中外边距塌陷现象,特别是在Vue布局中父子和兄弟元素的情况。详细讲述了塌陷的原因,提供了解决方案,包括避免BFC、使用padding、border等方法。
摘要由CSDN通过智能技术生成

参考文章

什么时候出现外边距塌陷

外边距塌陷,也叫外边距折叠,在普通文档流中,在垂直方向上的2个或多个相邻的块级元素(父子或者兄弟)外边距合并成一个外边距的现象,不过只有上下外边距才会有塌陷,左右外边距不会出现这种问题。
两种情况:

  1. 父子元素:子元素添加margin-top,但子元素并没有和父元素产生间隔,margin-top作用在了父盒子上
<template>
  <div class="father">
    <div class="son"></div>
  </div>
</template>

<script setup>
  import { ref, reactive } from 'vue'
</script>
<style lang="scss" scoped>
  .father {
    width: 500px;
    height: 300px;
    background-color: pink;
    .son {
      width: 100px;
      height: 100px;
      margin-top: 200px;
      background-color: skyblue;
    }
  }
</style>

在这里插入图片描述
或者父盒子和子盒子都添加margin-top,最后合并为一个margin-top取最大值,而不是2者之和

  .father {
    width: 500px;
    height: 300px;
    margin-top: 200px; //!!!
    background-color: pink;
    .son {
      width: 100px;
      height: 100px;
      margin-top: 100px; //!!
      background-color: skyblue;
    }
  }

在这里插入图片描述

  1. 兄弟元素:margin-bottom和margin-top合并,取最大值
<template>
  <div class="box1"></div>
  <div class="box2"></div>
</template>

<script setup>
  import { ref, reactive } from 'vue'
</script>
<style lang="scss" scoped>
  .box1 {
    width: 100px;
    height: 100px;
    margin-bottom: 100px;
    background-color: skyblue;
  }
  .box2 {
    width: 100px;
    height: 100px;
    margin-top: 100px;
    background-color: orange;
  }
</style>

在这里插入图片描述

具体的外边距计算方式

1.两个都是正数,取较大的值
2.两个都是负数,取绝对值较大的值
3.一正一负,取两个值得和

为什么会出现外边距塌陷

怎么解决外边距塌陷

父子关系

让他们不在同一个BFC中

1. 父元素不用margin,用padding

2. 给父元素添加border

相当于加了一堵墙不让margin-top冲出去

3. 给父元素开启BFC

开启BFC共有7种方式,具体介绍,点击进入

4. 给父元素添加clearfix

注意这里是before,换成after不好用
&::before {
display: grid;
content: ‘’;
}

<style lang="scss" scoped>
  .father {
    width: 500px;
    height: 400px;

    // overflow: hidden;
    background-color: pink;
    &::before {
      display: grid;
      content: '';
    }
    .son1 {
      width: 100px;
      height: 100px;
      margin-top: 100px;
      background-color: skyblue;
    }
  }
</style>

5. 子元素变为行内盒子:display: inline-block

6. 子元素加入浮动属性或定位

兄弟关系

加上BFC外壳

1. 只给一个元素设置边距

2. 底部元素变为行内盒子:display: inline-block

3. 底部元素设置浮动:float

4. 给下面的元素position设置为absolute或者fixed

5. 其中一个元素外套一个div并设置overflow:hidden;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值