当前位置:   article > 正文

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

css margin 合并

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

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

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

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

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

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

  1. <div class="box">
  2. <div class="box1">box1</div>
  3. <div class="box2">box2</div>
  4. <div class="box3">box3</div>
  5. </div>
  1. .box {
  2. width: 400px;
  3. height: 400px;
  4. background-color: antiquewhite;
  5. text-align: center;
  6. }
  7. .box1 {
  8. margin-top: 50px;
  9. width: 100px;
  10. height: 100px;
  11. line-height: 100px;
  12. background-color: rgba(0, 115, 255, 0.39);
  13. }
  14. .box2 {
  15. width: 100px;
  16. height: 100px;
  17. line-height: 100px;
  18. background-color: rgba(0, 255, 51, 0.232);
  19. margin-top: 20px;
  20. }
  21. .box3 {
  22. width: 100px;
  23. height: 100px;
  24. line-height: 100px;
  25. background-color: rgba(255, 196, 0, 0.232);
  26. margin-bottom: 20px;
  27. }

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

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

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

有三种方法:

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

  1. .box {
  2. width: 400px;
  3. height: 400px;
  4. background-color: antiquewhite;
  5. text-align: center;
  6. padding: 2px;
  7. }

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

  1. .box {
  2. width: 400px;
  3. height: 400px;
  4. background-color: antiquewhite;
  5. text-align: center;
  6. border-top: 1px solid red;
  7. }

 或

  1. .box {
  2. width: 400px;
  3. height: 400px;
  4. background-color: antiquewhite;
  5. text-align: center;
  6. border: 1px solid red;
  7. }

 

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

  1. .box {
  2. width: 400px;
  3. height: 400px;
  4. background-color: antiquewhite;
  5. text-align: center;
  6. overflow: hidden;
  7. }

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

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

  1. <div class="box">我是box元素</div>
  2. <div class="bro">我是box的兄弟元素</div>
  1. div {
  2. height: 200px;
  3. line-height: 200px;
  4. width: 200px;
  5. text-align: center;
  6. }
  7. .box {
  8. background-color: aquamarine;
  9. margin-bottom: 40px;
  10. }
  11. .bro {
  12. background-color: rgb(234, 250, 57);
  13. margin-top: 20px;
  14. }

     

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

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

 

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

  1. div {
  2. height: 200px;
  3. line-height: 200px;
  4. width: 200px;
  5. text-align: center;
  6. }
  7. .box {
  8. background-color: aquamarine;
  9. margin-bottom: 60px;
  10. }
  11. .bro {
  12. background-color: rgb(234, 250, 57);
  13. /* margin-top: 20px; */
  14. }

  

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/128938
推荐阅读
相关标签
  

闽ICP备14008679号