外边距塌陷(外边距合并)

外边距塌陷也称为外边距合并,是指两个在正常流中相邻(兄弟父子关系)的块级元素的外边距,组合在一起变成单个外边距,不过只有上下外边距才会有塌陷,左右外边距不会出现这种问题。(行内元素、浮动元素或绝对定位之间的外边距不会合并。)

1.父子关系()

  • 如果父元素在子元素的margin的同向上有padding或border的话,子元素的margin相对于父元素,`*否则相对于父元素以外的元素`*
<div class="father1">
    <div class="son1">子元素1</div>
</div>
.father1{
            width: 200px;
            height: 200px;
            background-color: yellow;
        }
        .son1{
            width: 150px;
            height: 150px;
            text-align: center;
            line-height: 150px;
            background-color: deepskyblue;
        }
​

1.1.给子元素添加margin-top

.son1{
            width: 150px;
            height: 150px;
            text-align: center;
            line-height: 150px;
            background-color: deepskyblue;
            margin-top: 50px;
        }
​

1.2注释掉子元素的margin-top,给父元素添加margin-top

.father1{
            width: 200px;
            height: 200px;
            background-color: yellow;
            margin-top: 50px;
        }

1.3给父元素和子元素都添加margin-top,且大小不一样

 .father1{
            width: 200px;
            height: 200px;
            background-color: yellow;
            margin-top: 50px;
        }
        .son1{
            width: 150px;
            height: 150px;
            text-align: center;
            line-height: 150px;
            background-color: deepskyblue;
            margin-top: 100px;
        }
​

2:相邻兄弟关系(上下相邻 左右不会出现外边距塌陷)

<div class="father1"></div>
<div class="father2"></div>
​
        .father1{
            width: 100px;
            height: 100px;
            background-color: yellow;
        }
        .father2{
            width: 100px;
            height: 100px;
            background-color: pink;
        }
​

        .father1{
            width: 100px;
            height: 100px;
            background-color: yellow;
            //加上margin
            margin-bottom: 100px;
        }
        .father2{
            width: 100px;
            height: 100px;
            background-color: pink;
            //加上margin
            margin-top: 50px;
        }
​

3.当外边距塌陷时,外边距之间的计算方式是怎样的?

3.1两个都是正数,取较大的值

3.2两个都是负数,取绝对值较大的值

3.3一正一负,取两个值得和

4.解决外边距塌陷的方法

第一种:给父元素增加内边距padding值


第二种方式:父元素增加边框border值


第三种方式:父元素增加overflow:hidden


第四种方式:给父元素或者子元素增加浮动,让其脱离标准流都可以


第五种:将父元素转变为行内块元素,display:inline-block


第六种:给父元素或者子元素定位都可以,原理同样是使其脱离标准流,不过只能用绝对定位和固定定位


第七种:给父盒子增加flex或者inline-flex

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值