I am a little confused about absolute positioning right now. I have always thought that if I position an element absolutely it would be positioned relative to it's parent element (in contrast to relative to it's usual position like relative positioning). During homework I now came across this situation and I'm confused:
<body>
<div> <!-- This is colored red in my example -->
...
</div>
<div style="position: absolute;"> <!-- This is colored green in my example -->
...
</div>
</body>
What I would expect: What I got:
Of course when I set an actual position with left
/right
/top
/bottom
I get what I would expect from an absolutely positioned element. So is position: absolute
just set to take the exact position it would be at without position: absolute
when not specified otherwise?
In position: relative , the element is positioned relative to itself. However, an absolutely positioned element is relative to its parent. An element with position: absolute is removed from the normal document flow. It is positioned automatically to the starting point (top-left corner) of its parent element.
Static - this is the default value, all elements are in order as they appear in the document. Relative - the element is positioned relative to its normal position. Absolute - the element is positioned absolutely to its first positioned parent. Fixed - the element is positioned related to the browser window.
Clearly, nothing can be absolute and relative at the same time. Either you want the element to position itself based on another ancestor's position or based on the page flow.
If you specify position:relative, then you can use top or bottom, and left or right to move the element relative to where it would normally occur in the document. Position Absolute: When you specify position:absolute, the element is removed from the document and placed exactly where you tell it to go.
To clarify:
"I have always thought that if I position an element absolutely it would be positioned relative to it's parent element"
Nope. If an element has position: absolute;
, it is positioned relative to the nearest parent in the DOM chain that has position: relative;
or position: absolute;
specified on it. If no parents have it (ie. they are all position: static
, which is the default), then it is positioned relative to the document (page).
When using position: absolute, always:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With