AarCee AarCee - 7 months ago 7
HTML Question

"position:absolute" usage in CSS

Consider an HTML:

<html>
<body>
<div id="outer"><div id="inner"></div></div>
</body>
<html>


And its CSS:

#inner {
height: 75px;
width: 75px;
background-color: red;
position: absolute;
margin-left: 20px;
}
#outer {
height: 1500px;
width: 150px;
background-color: green;
position:static;
margin-left: 100px;
}


From what I understand, the inner div should have a 20px left margin from the html element and not from the outer div as the outer div has a static position.
But it seems that the inner div always positions itself relative to outer div. What am I missing here?

If anyone can help, thanks.

EDIT:

Source: www.codecademy.com

Answer

position: absolute; removes the element from normal flow and positions itself relative to the closest positioned ancestor. If none exist, it positions itself to the initial containing block, which takes the dimensions of the viewport. Reference.

Nonetheless, for absolute elements, you should always specify the x and y dimensions (e.g., top and left), otherwise you may get some odd behavior, such as its positioning relative to a static ancestor element, which you are observing. See what happens when top and left are added:

#inner {
  height: 75px;
  width: 75px;
  background-color: red;
  position: absolute;
  top: 0;
  left: 0;
  margin-left: 20px;
}
#outer {
  height: 1500px;
  width: 150px;
  background-color: green;
  margin-left: 100px;
}
<html>

<body>
  <div id="outer">
    <div id="inner"></div>
  </div>
</body>
<html>

Comments