AarCee
AarCee

Reputation: 863

"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

Upvotes: 2

Views: 74

Answers (2)

timolawl
timolawl

Reputation: 5564

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>

Upvotes: 2

Voinicu Mihai
Voinicu Mihai

Reputation: 13

The element is positioned relative to its first positioned (not static) ancestor element. Thus the inner div will position itself based on the parent element containing it, in this case the "outer" div.

Upvotes: 0

Related Questions