Home > Article > Web Front-end > Why Does Absolute Positioning Inherit From the Immediate Parent in Nested Divs?
Absolute Absolute Positioning Anomaly
In a multi-layered layout involving absolute positioning, it's common to encounter a scenario where an inner div has absolute positioning relative to its immediate parent, which is also absolutely positioned within another div. However, in such a setup, the inner div inherits its absolute position from its immediate parent, leading to a seemingly unexpected behavior.
Consider the following HTML structure:
<code class="html"><div id="1st" style="position: relative;"> <div id="2nd" style="position: absolute;"> <div id="3rd" style="position: absolute;"></div> </div> </div></code>
Intuitively, one would expect the position of #3rd to be absolute relative to #1st, as #2nd is absolutely positioned within #1st. However, the reality is that #3rd's absolute positioning is inherited from #2nd. This is because position: absolute on #2nd resets its position relative to its parent, leading to #3rd being absolutely positioned within #2nd.
This behavior can be attributed to the CSS specificity rules. When a child element has an absolute position, its position is determined by the bounding box of its immediate parent. In this case, #3rd's position is defined by the bounding box of #2nd, and it is unaware of the absolute position of #2nd relative to #1st.
To resolve this issue and have #3rd absolutely positioned relative to #1st, it is necessary to make #3rd a direct child of #1st. In other words, the following HTML would result in the desired behavior:
<code class="html"><div id="1st" style="position: relative;"> <div id="3rd" style="position: absolute;"></div> </div></code>
In this case, #3rd's absolute position is determined by the position of its parent, #1st, which is what one would expect. It's important to note that resetting the position of a parent element through position: absolute also affects the positioning of its children, unless they are absolutely positioned relative to a different parent element.
The above is the detailed content of Why Does Absolute Positioning Inherit From the Immediate Parent in Nested Divs?. For more information, please follow other related articles on the PHP Chinese website!