给位于文档流中的.main 元素添加 margin-top 属性,但为什么脱离了文档流的.main-header 元素看起来似乎也同时受到了 margin-top 属性的作用?

2020-02-11 13:47:25 +08:00
 manyfreebug
代码及运行效果也可在 JS Bin 中查看:
  https://jsbin.com/nolatakoto/edit?html,css,output
主要有两个疑问:
1、给位于文档流中的.main 元素添加 margin-top 属性,
但为什么.main-header 元素看起来似乎也同时受到了 margin-top 属性的作用?

2、如果给 body 元素添加上 border 属性,此时.main-header 元素将回到设想中的位置,
为什么给 body 元素加上 border 属性就会发生这种变化呢?

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div class="main-header">Header</div>
  <div class="main">Main</div>
</body>
</html>
body {
  margin: 0;
  /*border: 2px solid red;*/
}

.main-header {
  position: absolute;
  background: #ccc;
}

.main {
  font-size: 50px;
  margin-top: 50px;
  background: blue;
}
1648 次点击
所在节点    CSS
6 条回复
rain0002009
2020-02-11 14:51:39 +08:00
别问了 大家都知道怎么决绝 很少有人知道为什么
waiaan
2020-02-11 14:53:25 +08:00
BFC 了解一下(我也不理解)
rabbbit
2020-02-11 14:58:54 +08:00
margin 合并导致 margin-top 飞出去了

给 body 加个样式就清楚了
body {outline: 4px solid yellow; }
learnshare
2020-02-11 15:30:15 +08:00
>An absolutely positioned element is an element whose computed position value is absolute or fixed. The top, right, bottom, and left properties specify offsets from the edges of the element's containing block. (The containing block is the ancestor relative to which the element is positioned.) If the element has margins, they are added to the offset. The element establishes a new block formatting context (BFC) for its contents.

https://developer.mozilla.org/en-US/docs/Web/CSS/position#Types_of_positioning
morethansean
2020-02-11 15:45:23 +08:00
涉及到绝对元素的定位、块级格式化上下文和外边距折叠。
这个不是 5 年前前端面试时候 css 盒模型必考内容之一么,为什么楼上说很少有人知道为什么……
manyfreebug
2020-02-11 16:41:52 +08:00
@rabbbit .main 元素与 body 元素产生了外边距重叠的现象,且.main-header 元素不存在应用了定位的祖先元素,因此该元素相对于紧邻的祖先元素(<body>元素)绝对定位。所以让.main-header 看起来也受到了 margin-top 的作用。
是这样?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/643707

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX