css外边距塌陷(合并)

[1]相邻块元素垂直外边距的合并
1.当上下相邻的二个块元素相遇时,如果上面的元素有下外边距margin-buttom
2.下面的元素有上外边距margin-top,则他们之间的垂直间距不是margin-bottom与mtop之和
3.取二者值中的较大者的这种现象称之为相邻块元素垂直外边距的合并
解决方法
尽量只给一个盒子加margin
在这里插入图片描述

<style>
        .a1{
            width: 200px;
            height: 200px;
            background-color: aquamarine;
            margin-bottom: 100px;
        }
        .a2{    
            margin-top: 50px;
            width: 200px;
            height: 200px;
            background-color: darkorange;
        }
    </style>
</head>
<body>
    <div class="a1"></div>
    <div class="a2"></div>
</body>

运行结果:
在这里插入图片描述
【2】嵌套块元素垂直外边距的合并
1、对于二个嵌套关系的块元素,如果父元素没有上内边距或边框
2、父元素的上外边距会与子元素的上外边距发生合并
3、合并值为二者中的较大者
解决方法:
1、可以给父元素定义上边框border-top
2、可以给父元素定义上内边距padding-top
3、可以给父元素添加overflow:hidden;
4、转为行内块元素
5、设置浮动
其他:浮动、固定、绝对定位的盒子

<style>
        .father{
            width: 300px;
            height: 300px;
            background-color: aquamarine;
            margin-top: 100px;
            /* border: 1px solid; */
            /* padding: 1px; */
            overflow: hidden;
        }
        .son{
            margin-top: 150px;
            width: 100px;
            height: 100px;
            background-color: blue;
        }
     </style>
</head>
<body>
    <div class="father">
        <div class="son"></div>
    </div>
</body>

外边距塌陷的运行结果:
不管是子盒子还是父盒子都会被往下顶;
子盒子设置了margin-top=100px,会把父盒子往下顶100px,即:坑爹行为
如果父亲设置了margin-top=200px,则父盒子会往下移动200px
在这里插入图片描述

消除塌陷后运行结果:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值