margin的特别之处

特别之处:只会出现在上下,不会出现在左右

上下margin传递

  1. 如果块级元素的顶部线和父元素的顶部线重叠,那么块级元素的margin-top的值会传递给父元素
<style>
.father {
     200px;
    height: 200px;
    background-color: red;
 }
  .son {
    height: 100px;
     100px;
    background-color: blue;
    margin-top: 20px;  <--子元素设置margin,会传递给父元素,然后整体向下移动-->
 }
</style>
<div class="father">
   <div class="son"></div>
</div>
  1. 如果块级元素的底部线和父元素的底部线重叠,并且父元素的高度为auto,那么这个块级元素的margin-bottom值会传递给父元素

防止出现传递的问题

  1. 给父元素设置padding-top或者padding-bottom(原因: 传递需要满足边线重叠,设置padding就不会边线重叠)

  2. 给父元素设置border(原因:也是边线不重叠)

  3. 触发BFC:设置overflow为auto或者hidden

上下margin的折叠

  1. 垂直方向上相邻的2个margin(margin-top、margin-bottom)有可能合并为1个margin,这种现象叫合并(collapse),水平方向上没有这种现象。(取最大值

  2. 当然,还有一种特殊的情况,就是父子元素都设置了margin(top、bottom)值,子元素传递给父元素,然后取最大值。

<!--同时给父子元素设置margin-top,子元素传递给父元素,然后比较取最大值-->
<style>
.father {
     200px;
    height: 200px;
    background-color: red;
    margin-top: 30px;
 }
  .son {
    height: 100px;
     100px;
    background-color: blue;
    margin-top: 20px;  
 }
</style>
<div class="father">
   <div class="son"></div>
</div>

设计建议:

margin是用来设计兄弟元素的距离,父子元素使用padding来设置距离。

原文地址:https://www.cnblogs.com/xyf724/p/13456088.html