-2

当内部元素放置上边距时,容器被拉下,因此白色部分出现在页面顶部。我怎样才能防止那个白色部分?

.container {
  background: red;
  height: 500px;
}

.inner {
  margin-top: 100px;
  height: 50px;
  background: yellow;
}
Why there is white section in here ??
<div class="container">
  <div class="inner"></div>
</div>

4

3 回答 3

2

在外部元素上将溢出设置为自动。您在示例中看到边距缩小

父级和第一个/最后一个子级 - 如果没有创建边框、填充、内联部分、块格式化上下文或间隙以将块的 margin-top 与其第一个子块的 margin-top 分开;或者没有边框、填充、内联内容、高度、最小高度或最大高度来将块的边距底部与其最后一个子块的边距底部分开,然后这些边距折叠。折叠的边距最终在父级之外。

.container {
  background: red;
  height: 500px;
  overflow: auto;
}

.inner {
  margin-top: 100px;
  height: 50px;
  background: yellow;
}
Why there is white section in here ??
<div class="container">
  <div class="inner"></div>
</div>

于 2019-04-16T18:32:51.587 回答
0

由于CSS Box Model ,您得到的结果是预期的。

CSS 盒子模型本质上是一个包裹每个 HTML 元素的盒子。它包括:边距、边框、填充和实际内容。

Box Model不同部分的解释:

内容- 显示文本和图像的框的内容

填充- 清除内容周围的区域。填充是透明的

边框- 围绕填充和内容的边框

边距- 清除边界外的区域。边距是透明的

请参阅此代码段中说明的边距和填充之间的区别:

.container {
  background: red;
  height: 500px;
}

.inner {
  height: 50px;
  background: yellow;
}

.margin {
  margin-top: 100px;
}

.padding {
  padding-top: 100px;
}
<div class="container">
  <div class="inner margin">
    Inner div has a margin-top
  </div>
</div>
<hr>
<div class="container">
  <div class="inner padding">
    Inner div has a padding-top
  </div>
</div>
<hr>
<div class="container">
  <div class="inner">
    Inner div has no padding/margin
  </div>
</div>

于 2019-04-16T18:37:41.767 回答
0

删除div .inner 上的margin-top:100px

你也可以使用 margin-top: 0; ,或顶部:0;但没必要……

演示

尝试这个:

html,body {margin:0}

.container {
background: red;
height: 500px;
}

.inner {
/*margin-top: 100px;*/
/*margin-top: 0;*/
/*top:0;*/
height: 50px;
background: yellow;
}

// ---------------      

<div class="container">
  <div class="inner"></div>
</div>
于 2019-04-16T18:37:52.673 回答