"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does Nested Absolute Positioning Cause Elements to Refer to Their Parent Instead of the Grandparent?

Why Does Nested Absolute Positioning Cause Elements to Refer to Their Parent Instead of the Grandparent?

Published on 2024-11-07
Browse:910

Why Does Nested Absolute Positioning Cause Elements to Refer to Their Parent Instead of the Grandparent?

Nested Positioning: Absolute Within Absolute

Nested absolutely positioned elements can exhibit unexpected behavior in CSS. Consider this scenario:

  • A first div (#1st) with position: relative
  • A second div (#2nd) absolutely positioned relative to #1st
  • A third div (#3rd) absolutely positioned within #2nd

Q: Why is #3rd absolutely positioned relative to #2nd instead of #1st?

A: Because position: absolute within an absolutely positioned element resets the relative position for its children.

This property effectively overrides the relative positioning of #1st for #3rd, making it position absolute relative to its direct parent, #2nd.

To achieve your desired behavior, where #3rd is absolutely positioned relative to #1st, you would need to make #3rd a direct child of #1st.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3