margin塌陷问题

今天在CSS3练习弹性盒子中想起了margin的塌陷问题。在这里回忆一下…

margin 塌陷是在父级相对于浏览器进行定位时但子级没有相对于父级定位,子级相对于父级就像塌陷了一样,父子嵌套元素垂直方向的 margin,父子元素是结合在一起的,他们两个会取其中最大的值。
1)当两个盒子垂直并列在一起时(不常见)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
    *{
         margin: 0; 
         padding: 0; 
    }
    .box1{ 
         width: 200px; 
         height: 200px; 
         background: yellowgreen;
     } 
    .box2{ 
         width: 200px; 
         height: 200px; 
         background: gray; 
    }
    </style>
</head>
<body>
    <div class="box1">box1</div>
    <div class="box2">box2</div>
</div>
</body>
</html>

image.png
如果我将box1的margin-bottom设置为80px,而box2的margin-top属性设置为50px,那么box1与box2是相距130px还是什么呢?对于大多数初学者而言,一眼觉得是130px,而非80px。这就是margin的塌陷问题。

    <div class="box1">box1</div>
    <div class="box2">box2</div>
*{
         margin: 0; 
         padding: 0; 
    }
    .box1{ 
         width: 200px; 
         height: 200px; 
         background: yellowgreen;
         margin-bottom: 80px;
     } 
    .box2{ 
         width: 200px; 
         height: 200px; 
         margin-top: 50px;
         background: gray; 
    }

我们来看看效果
image.png
2)一个盒子里面嵌套另一个盒子时,在里面的盒子添加margin属性(常见)
代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
    *{
         margin: 0; 
         padding: 0; 
    }
    .box1{
        width:400px;
        height:400px;
        background: #f40;
    }
    .box2{
        width:200px;
        height:200px;
        margin-top: 20px;
        background: #0ff;
    }
    </style>
</head>
<body>
    <div class="box1">
        <div class="box2"></div>
    </div>
</body>
</html>

效果呢,看了会不会很惊讶呢…
image.png
其实吧,这明显是margin塌陷。
margin-top:20px;加到box1或者box2效果一样。那么怎么才能将margin他先解决呢??
我在全网搜了搜,一共以下三种方法:
1.在父级盒子加border属性使box2不再与box1贴合

.box1{
        width:400px;
        height:400px;
        border:1px solid black;
        background: #f40;
    }

效果呢,就变成我们一开始想象的那样。
image.png

2.为父级盒子添加overflow:hidden;position: absolute;float: left; display:inline-block;
3.为父级盒子设定padding值。
其实这三种方法的共同点都是使box2与box1不贴合。促使子级盒子相对于父级定位。
感觉学到点东西的,麻烦点个赞,关注一波也可以。如果有错,请评论或者私信我哈!!!

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值