DIV with position:absolute dragged by a subsequent object

  Kiến thức lập trình

Why is div1 being pushed from the top edge? It seems to follow div2 margin setting.
I would expect div1 to behave independently of div2 (i.e. stick to the top). Is there any way to keep div1 at the top of the screen without using top:0.

<html>
<head>
    <style>
        * { margin:0; padding:0; border:0; }
        .div1 { margin:0rem; background:red; position:absolute; }
        .div2 { margin:3rem; background:grey; }
    </style>
</head>
<body>
    <div class="div1">div1</div>
    <div class="div2">div2</div>
</body>
</html>

Screenshot of the code above

New contributor

AdamJ is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT