CSS解决外边距塌陷问题

CSS外边距塌陷

<div class="father">
    <div class="son"></div>
</div>
当我们为子元素设置margin-top可能会遇到以下问题:

在这里插入图片描述

在为子元素设置margin-top会将父元素一起拖下来

这是因为:
  1. 元素为嵌套元素(即父元素与子元素)
  2. 父元素与子元素在垂直方向上的外边距合并(margin-top和margin-bottom)
从而产生了外边距塌陷
要解决这个问题,我们可以使用以下方法

1. 父元素添加顶部padding

CSS样式
.father {
    padding-top: 1px; /* 任意大小均可 */
    width: 500px;
    height: 500px;
    background-color: red;
}
.son{
    width: 100px;
    height: 100px;
    background-color: blue;
}

2. 父元素添加顶部border

CSS样式
.father {
    border-top: 1px solid transparent;
    width: 500px;
    height: 500px;
    background-color: red;
}

.son {
    margin-top: 200px;
    width: 100px;
    height: 100px;
    background-color: blue;
}

3. 父元素/子元素设置为绝对定位

CSS样式
.father {
    position: absolute;
    width: 500px;
    height: 500px;
    background-color: red;
}

.son {
    /* position: absolute; */
    margin-top: 200px;
    width: 100px;
    height: 100px;
    background-color: blue;
}

4. 父元素设置overflow: auto/hidden

CSS样式
.father {
    overflow: auto;
    /* overflow: hidden; */
    width: 500px;
    height: 500px;
    background-color: red;
}

.son {
    margin-top: 200px;
    width: 100px;
    height: 100px;
    background-color: blue;
}

5. 父元素设置display: flex

CSS样式
.father {
    display: flex;
    width: 500px;
    height: 500px;
    background-color: red;
}

.son {
    margin-top: 200px;
    width: 100px;
    height: 100px;
    background-color: blue;
}

6. 父元素/子元素设置为浮动元素

CSS样式
.father {
    float: left;
    display: flex;
    width: 500px;
    height: 500px;
    background-color: red;
}

.son {
    /* float: left; */
    margin-top: 200px;
    width: 100px;
    height: 100px;
    background-color: blue;
}

7. 父元素设置display: table

CSS样式
.father {
    display: table;
    width: 500px;
    height: 500px;
    background-color: red;
}

.son {
    margin-top: 200px;
    width: 100px;
    height: 100px;
    background-color: blue;
}

实际效果

实际效果图

希望这篇文章能对您有所帮助!
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值