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

前端 未结 5 599
难免孤独
难免孤独 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:52

    This is another instance of the phenomenon known as margin-collapsing.

    I'll try to explain what is happening:

    When you move div.absolute with position absolute, it pulls it out of the flow of the content. This causes the first h1 to act as the first-child of its parent, which is body in this case.

    The h1's margin then gets collapsed outside the body, due to margin-collapsing. That is why top: 0; is not in the upper-left of the viewport. It is in the upper left of the body.

    If you need to get this to work, then add a html {position: relative; overflow: hidden:}.

提交回复
热议问题