margin折叠的计算方法

css:
clipboard.png
html:
clipboard.png
结果:
clipboard.png
问题:
我所理解的边距重叠计算遵守以下规则(不知道有没有问题)
clipboard.png

按照这个计算结果为:粉红色的盒子与上面的距离应该为 800-50=750px ,但实际结果为 0 ,所以很晕,求解。

问题2:
css:
clipboard.png

html:
clipboard.png

结果:
clipboard.png

问题: h1标签上的白色间隙为2px.为什么?
第一个思路,先考虑ul和li的折叠,折叠结果为+10px,再与h1的-18px折叠,最终为 -10px;
第二个思路,先考虑ul和h1,折叠结果为-18px,在与li的+20px折叠,最终为2px。
哪里有问题呢?求解。

阅读 2.6k
2 个回答
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <style>
      *{
        margin: 0;
        padding: 0;
      }
      .fl{
        float:left;
      }
      .outer{
        width: 800px;
        /*height: 300px; */
        /*把父级的高度去掉,你再试试就明白了*/
        margin-bottom: -50px;
        background-color: yellow;
        /*overflow: hidden;*/
      }
      .inner{
        width: 400px;
        height: 300px;
        margin-bottom: 300px;
        margin-top: 300px;
        background-color: black;
      }
    </style>
  </head>
  <body>
    <div class="" style="width: 100%; height: 100px; background-color:pink;">

    </div>
    <div class="outer">
      <div class="inner">

      </div>
    </div>
    <div class="" style="width: 100%; height: 100px; background-color:pink;">

    </div>
  </body>
</html>

因为父级设置了高度,所以子集的margin-bottom不是没有了,而是被父级的高度限制,作用不到下边的文档流上。

第二个问题:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <style media="screen">
      *{
        margin: 0;
        padding: 0;
      }
      li{
        margin-bottom: 20px;
        background-color: #EE3;
      }
      ul{
        /*margin-bottom: -10px;*/
        background-color: #AF3
      }
      h1{
        margin-top: -18px;
        background-color: #CCC;
      }
    </style>
  </head>
  <body>
    <ul id="ul">
      <li>A list item</li>
      <li>Another list item</li>
    </ul>
    <h1 id="h1">title</h1>
  </body>
</html>

首先你ul没设置height,这个时候你注释掉ul的-10 注释掉h1的-18 会发现ul和h1之间有20 ,这个20是第二个li的margin-bottom,
然后你加上h1的-18,看一下是不是有只有2px了,这是因为ul和h1是被认定为相邻元素的,这时遵循margin合并的规则,取大的值,所以20-18 只有2 ,即便你加上ul的-10也是一样的。
你可以把ul的-10改成-30或者-50, 这是后h1的-18就不生效了

inside的margin作用于outer里,outer的底部margin是-50px,而粉色盒子顶部的margin是50px。-50+50=0px

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题