外边距塌陷如何解决

文章探讨了在CSS布局中,由于父子级标签间的外边距导致的父级元素位置下移问题。提出了几种解决方案,包括取消子级外边距并使用父级padding,设置父级overflow为hidden,以及使用父级的border来避免塌陷。这些方法可以有效地防止因子元素外边距而影响整体布局。
摘要由CSDN通过智能技术生成

场景:父子级的标签,子级的添加上外边距会产生塌陷问题。

现象:导致父级一起向下移动。

<style>
    .father{
        width:300px;
        height:300px;
        background-color:pink;
    }
    .son{
        width:100px;
        height:100px;
        background-color:#000;
        margin-top:50px;
    }
</style>

<div class="father">
    <div class="son">son</div>
</div>

解决方法:

  • 取消子级margin,父级设置padding
<style>
    .father{
        width:300px;
        height:300px;
        background-color:pink;
        padding-top:50px;
        box-sizing:border-box;
    }
    .son{
        width:100px;
        height:100px;
        background-color:#000;
       /* margin-top:50px; */
    }
</style>

<div class="father">
    <div class="son">son</div>
</div>
  • 父级设置overflow:hidden
<style>
    .father{
        width:300px;
        height:300px;
        background-color:pink;
        overflow:hidden;
    }
    .son{
        width:100px;
        height:100px;
        background-color:#000;
        margin-top:50px;
    }
</style>

<div class="father">
    <div class="son">son</div>
</div>
  • 父级设置border-top
<style>
    .father{
        width:300px;
        height:300px;
        background-color:pink;
        border-top:1px solid pink;
    }
    .son{
        width:100px;
        height:100px;
        background-color:#000;
        margin-top:50px;
    }
</style>

<div class="father">
    <div class="son">son</div>
</div>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值