CSS常见margin塌陷问题和解决方法

margin塌陷问题

当两个盒子在垂直方向上设置margin值时,会出现一个有趣的塌陷现象。

1、垂直并列

首先设置两个DIV,并为其制定宽高和背景色方便观看

 <style>
       /*CSS部分*/
       *{
           margin: 0;
           padding: 0;
       }
       .box1{
           width: 200px;
           height: 200px;
           background-color: aquamarine;
       }
       .box2{
           width: 200px;
           height: 200px;
           background-color: bisque;
       }
    </style>
</head>
<body>
    <!--html部分-->
    <div class="box1">box1</div>
    <div class="box2">box2</div>
</body>

在这里插入图片描述

对box1我们为其设置margin-bottom:50px;
对box2我们为其设置margin-top: 40px;

    <style>
       /*CSS部分*/
       *{
           margin: 0;
           padding: 0;
       }
       .box1{
           width: 200px;
      
           height: 200px;
           margin-bottom: 50px;
           background-color: aquamarine;
       }
       .box2{
           width: 200px;
           height: 200px;
           margin-top: 40px;
           background-color: bisque;
       }
    </style>
</head>
<body>
    <!--html部分-->
    <div class="box1">
        box1
    </div>
    <div class="box2">
        box2
    </div>
</body>

我们肯定会很理所当然的认定这两个盒子之间的距离为90px,事实上并非如此.
如下图所示:
在这里插入图片描述
两盒子之间的距离仅是50px,也就是说两盒子之间的margin出现了重叠部分,故而我们可以得出:垂直之间塌陷的原则是以两盒子最大的外边距为准。

2、嵌套关系(父级元素塌陷)

    <style>
        /*css部分*/
        *{
            margin: 0;
            padding: 0;
        }
        .box{
            width: 300px;
            height: 400px;
            background-color: aliceblue;
        }
        .box1{
            width: 250px;
            height: 250px;
            background-color: bisque;
        }
    </style>
</head>
<body>
    <!--html部分-->
    <div class="box">
        <div class="box1"></div>
    </div>
</body>

效果图
在这里插入图片描述
当为子盒子添加margin-top:100px;时会发生如下情况:
在这里插入图片描述
子盒子和父盒子之间并没出现期望的10px间隙而是父盒子与子盒子一起与页面顶端产生了10px间隙(即父级盒子往下塌陷了10px)。

解决方法:
(1)为父盒子设置border,为外层添加border后父子盒子就不是真正意义上的贴合 (可以设置成透明:border:1px solid transparent)。

(2)为父盒子添加overflow:hidden;

(3)为父盒子设定padding值;

(4)为父盒子添加position:fixed;

(5)为父盒子添加 display:table;

(6)利用伪元素给子元素的前面添加一个空元素

.son:before{ content:"";
             overflow:hidden; }
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值