V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Can I use?
http://caniuse.com/
Less
http://lesscss.org
Cool Libraries
Bootstrap from Twitter
Jetstrap
manyfreebug
V2EX  ›  CSS

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

  •  
  •   manyfreebug · 2020-02-11 13:47:25 +08:00 · 1631 次点击
    这是一个创建于 1507 天前的主题,其中的信息可能已经有所发展或是发生改变。
    代码及运行效果也可在 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;
    }
    
    6 条回复    2020-02-11 16:41:52 +08:00
    rain0002009
        1
    rain0002009  
       2020-02-11 14:51:39 +08:00
    别问了 大家都知道怎么决绝 很少有人知道为什么
    waiaan
        2
    waiaan  
       2020-02-11 14:53:25 +08:00
    BFC 了解一下(我也不理解)
    rabbbit
        3
    rabbbit  
       2020-02-11 14:58:54 +08:00   ❤️ 1
    margin 合并导致 margin-top 飞出去了

    给 body 加个样式就清楚了
    body {outline: 4px solid yellow; }
    learnshare
        4
    learnshare  
       2020-02-11 15:30:15 +08:00   ❤️ 1
    >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
        5
    morethansean  
       2020-02-11 15:45:23 +08:00   ❤️ 1
    涉及到绝对元素的定位、块级格式化上下文和外边距折叠。
    这个不是 5 年前前端面试时候 css 盒模型必考内容之一么,为什么楼上说很少有人知道为什么……
    manyfreebug
        6
    manyfreebug  
    OP
       2020-02-11 16:41:52 +08:00
    @rabbbit .main 元素与 body 元素产生了外边距重叠的现象,且.main-header 元素不存在应用了定位的祖先元素,因此该元素相对于紧邻的祖先元素(<body>元素)绝对定位。所以让.main-header 看起来也受到了 margin-top 的作用。
    是这样?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4453 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 01:05 · PVG 09:05 · LAX 18:05 · JFK 21:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.