Why does body positioning affect absolutely positioned elements?

So, with the code below, when I change the border of the bar, the position of foo changes. But this only happens when the body is relatively positioned. If I statically position the body, then the position of foo no longer depends on the border of the bar. Can someone tell me what is going on?

<!DOCTYPE html> <html> <head> <style type="text/css"> * { margin:0; } body { position:relative; } #foo { position:absolute; top:50px; left:50px; } #bar { margin:100px; } </style> </head> <body> <div id="foo">asdf</div> <div id="bar">asdf</div> </body> </html> 
+6
source share
2 answers

Absolutely positioned elements are tied by their closest absolutely or relatively positioned parent.

EDIT: For additional clarity on margin, please see my comment below.

EDIT2: This also applies to fixed position elements.

+5
source

Jrod nailed it, by default, positioning is always at the top left of the browser window. The default positioning is Relative, since each element added (children) will follow the same recommendations.

You specified #foo coordinates, while all that #bar you gave is a field that should be respected in relation to the body.

0
source

Source: https://habr.com/ru/post/890250/


All Articles