margin塌陷与margin合并

margin塌陷

  • 先举个例子
<style>
       
     .wrapper{
         width:200px;
         height:200px;
         background-color:red;
         margin-top:100px;
     }
     .box{
        width:50px;
         height:50px;
         background-color:#eee;
         opacity:0.8;
         margin-top: 100px;

     }
    </style>
</head>
<body >
        <div class="wrapper">
            <div class="box"></div>
        </div>
<body>

效果如下:
在这里插入图片描述

距离上边100px,现在给里面的小方块设置margin-top:100px;发现两个方块位置没动;
而当给里面的小方块设置margin-top:150px;小方块带着大方块往下移动了50px

  • 原理:父子嵌套元素在垂直方向的margin,父子元素是结合在一起的,他们两个的margi会取其中最大的值。
  • 正常情况下,父级元素应该相对浏览器进行定位,子级相对父级定位。
    但由于margin的塌陷,父级相对浏览器定位。而子级没有相对父级定位,子级相对父级,就像坍塌了一样。

margin塌陷解决方法

  1. 给父级设置边框或者内边距
  • 不建议使用,会增加px
 .wrapper{
         width:200px;
         height:200px;
         background-color:red;
         margin-top:100px;
         border-top: 1px solid red;
         /* padding-top: 1px; */
     }

效果如下:
在这里插入图片描述
2. 触发bfc(块级格式上下文),改变父级的渲染规则

  • 方法:

改变父级的渲染规则有以下四种方法,给父级盒子添加

①position:absolute/fixed

②display:inline-block;

③float:left/right

④overflow:hidden
  • 这四种方法都能触发bfc,但是使用的时候都会带来不同的麻烦,具体还需根据具体情况选择没有影响的方法,来解决margin塌陷。

margin合并

  • 原因:两个兄弟结构的元素在垂直方向上的margin是合并的
  • 代码如下
<style>
        * {
            padding: 0;
            margin: 0;
        }

        .box{
            height: 30px;
            margin-bottom: 100px;
            background-color: red;
        }

        .box1 {
            height: 30px;
            margin-top: 100px;
            background-color: blue;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <div class="box1"></div>
  

 </body>

效果如下:
在这里插入图片描述
box和box1中间只有100px

  • margin合并问题也可以使用bfc(块级格式化上下文)解决
  1. 给box1加上一层父级元素并加上overflow:hidden;
 <div class="wrapper">
        <div class="box1"></div>
    </div>
 .wrapper{
            overflow:hidden;
        }
  1. 给两个盒子都加一层父级再加bfc
    <div class="wrapper">
        <div class="box"></div>
    </div>
    <div class="wrapper">
        <div class="box1"></div>
    </div>
  • 虽然可以解决问题,但是这两种方法都改变了HTML结构,在开发中是不能采用的。

  • 所以在实际应用时,在margin合并这个问题上,我们一般不用bfc,而是通过只设置上面的元素的margin-bottom来解决距离的问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值