为什么margin子元素会影响body元素?

时间:2015-12-31 18:16:42

标签: html css margin

请您解释一下为什么body会受到其子女边际的影响?我不喜欢这种行为。在我看来,孩子div的边际应该从其父母的边界到其边界计算。

例如: https://jsfiddle.net/2yejm7L5/

您可以看到蓝色的div影响绿色body的边距,然后您看到html背景为红色,我不希望这样。

就我而言,我不想编辑body CSS属性

1 个答案:

答案 0 :(得分:0)

如果您将body css修改为以下内容,您将实现目标:

body {
  background-color: green;
  height: 100%;
  width:100%;
  margin:0;
  position: absolute;
}

/ *另一种技术* / 删除上边距:50px,并用另一个div包装你的toto div并给它填充顶部:50px;如下所示:

html {
  background-color: red;
  height: 100%;
}
body {
  background-color: green;
  height: 100%;
  margin:0;
}

#container { padding-top:50px; }

.toto {
  background-color: blue;
  width: 100px;
  height: 100px;
}
<div id="container">
  <div class="toto">

  </div>
</div>