CSS查缺补漏之《如何优雅解决margin垂直方向塌陷与合并问题?》

一:父子元素之间margin垂直方向塌陷问题

在处理margin垂直方向问题时,经常会遇到在给子元素设置margin时,导致效果出现在了父元素上;如下代码所示:

代码原义是想实现三方面:

① 将box1的margin-top调为50px,使其与父元素之间形成空隙;

② 将box2的margin-top调为20px,使其与兄弟元素box1之间形成空隙;

③ 将box3的margin-bottom调为20px,使其与父元素之间形成空隙;

<div class="box">
  <div class="box1">box1</div>
  <div class="box2">box2</div>
  <div class="box3">box3</div>
</div>
    .box {
      width: 400px;
      height: 400px;
      background-color: antiquewhite;
      text-align: center;
    }
    .box1 {
      margin-top: 50px;
      width: 100px;
      height: 100px;
      line-height: 100px;
      background-color: rgba(0, 115, 255, 0.39);
    }
    .box2 {
      width: 100px;
      height: 100px;
      line-height: 100px;
      background-color: rgba(0, 255, 51, 0.232);
      margin-top: 20px;
    }
    .box3 {
      width: 100px;
      height: 100px;
      line-height: 100px;
      background-color: rgba(255, 196, 0, 0.232);
      margin-bottom: 20px;
    }

 从上述代码可以看到,效果出现与预期不同的情况:

① 给第一个子元素box1设置了margin-top值后,并没有起作用,却导致了父元素的margin-top存在;

该种情况被称为父子元素在垂直方向的margin塌陷问题,如何解决此问题?

有三种方法:

给父元素设置不为0的padding值

.box {
   width: 400px;
   height: 400px;
   background-color: antiquewhite;
   text-align: center;
   padding: 2px;
}

 ② 给父元素设置宽度不为0的border值

.box {
   width: 400px;
   height: 400px;
   background-color: antiquewhite;
   text-align: center;
   border-top: 1px solid red;
}

 或

.box {
   width: 400px;
   height: 400px;
   background-color: antiquewhite;
   text-align: center;
   border: 1px solid red;
}

 

③ 给父元素设置CSS样式overflow: hidden

.box {
   width: 400px;
   height: 400px;
   background-color: antiquewhite;
   text-align: center;
   overflow: hidden;
}

二:兄弟元素之间margin垂直方向合并问题

在处理兄弟元素问题时,若上面的兄弟元素设置了margin-bottom下面的兄弟元素设置了margin-top,则最后的margin值会取二者之间的最大值,而不是将二者相加,该种现象称为margin合并问题;

 <div class="box">我是box元素</div>
 <div class="bro">我是box的兄弟元素</div>
    div {
      height: 200px;
      line-height: 200px;
      width: 200px;
      text-align: center;
    }
    .box {
      background-color: aquamarine;
      margin-bottom: 40px;
    }
    .bro {
      background-color: rgb(234, 250, 57);
      margin-top: 20px;
    }

     

可以看到,在二者之间只有40px的空隙,产生了合并现象。如何解决此问题?

最好的方法是指设置一个,计算好兄弟元素之间的margin,只设置一方即可~

 

如上述代码只给第一个兄弟元素添加margin-bottom为60px即可,

    div {
      height: 200px;
      line-height: 200px;
      width: 200px;
      text-align: center;
    }
    .box {
      background-color: aquamarine;
      margin-bottom: 60px;
    }
    .bro {
      background-color: rgb(234, 250, 57);
      /* margin-top: 20px; */
    }

  

猜你喜欢

转载自blog.csdn.net/ks795820/article/details/131221458