Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does relatively positioning the body influence absolutely positioned elements?

Tags:

html

css

So with the code below, when I change the margin of 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 margin of bar. Can anyone tell me what's 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>
like image 626
zjmiller Avatar asked Jun 10 '11 19:06

zjmiller


1 Answers

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

EDIT: For added clarity about the margin please see my comment below.

EDIT2: This also applies to elements with a fixed position.

like image 77
Jrod Avatar answered Nov 13 '22 04:11

Jrod