Why doesn't top: 0 work on absolutely-positioned elements relative to body?

前端 未结 5 605
难免孤独
难免孤独 2020-12-31 04:36

You can see in the code below that the h1 pushes down the body and the absolutely-positioned block .absolute does not stick to the top. But you als

5条回答
  •  天命终不由人
    2020-12-31 04:48

    This is interesting behavior with little documentation to be found online (at least on a basic search).

    I'll start by saying I don't know the reason why the absolutely positioned box doesn't align to the corner of body, as it would be expected to do. But here are a few observations:

    1. The expected positioning works on IE11. The gap exists in Chrome and FF.

    2. If you remove position: relative from body, the expected positioning works (as tested in Chrome, FF & IE11). demo

    3. If you apply just 1px padding to body, it also works cross-browser. demo

    4. If you add a border to body, it also works. demo


    UPDATE

    As a quick addendum to @BoltClock's accepted answer, this problem could have been easily illustrated and understood by just adding a background color to the root element in the original code...

    html { background-color: red; }
    

    demo

    ... and by removing the default margin on the h1:

    h1 { margin: 0; }
    

    demo

提交回复
热议问题