关于margin重合的几种解决办法

1  垂直的两个DIV

<div class="top"></div>
<div class="bottom"></div>
.top{width: 100px;height:100px;background: red;margin-bottom: 20px}
.bottom{width: 100px;height:100px;background: green;margin-top: 40px}

            

top                      bottom

  我们会发现top的margin-bottom和bottom的margin-top重合了,且值为max(margin-top,margin-bottom)。例子中即为40px,可是有时候我们需要实现20+40的效果怎么来实现呢,两种方法:

  • clear: left; float: left; on siblings (right works too)  inherit不行
  • display: inline-block on siblings (inline-table works too)

  在两个div上都加上clear: left; float: left;或者display: inline-block(两个div中任意一个加了都行)

  2:父元素包含子元素

  

<div class="div1">
    <div class="div2"></div>
</div>
.div1{width: 200px;height: 200px;background: red;}
.div2{width: 100px;height: 100px;background: green;margin:50px }

  

我们会发现并不是我们想要的结果;解决方法有如下几种:

  • overflow: hidden (or anything else than auto
  • padding: 1px (or any value greater than 0); some browsers even support sub-pixel values)
  • border: 1px solid transparent (or any border)
  • display: inline-block (inline-table works too)
  • float: left (right works too)

参考链接:http://tympanus.net/codrops/2013/07/17/troubleshooting-css/#article-margin

这是我第一次阅读英文文档,虽然看的比较慢,却发现讲的确实比中文的好,也体会到了度英文文档的那种逼格。啊哈哈!

  

原文地址:https://www.cnblogs.com/djlxs/p/5032508.html