Home >Web Front-end >CSS Tutorial >Why does an absolutely positioned element inherit its positioning from its closest absolutely positioned parent, not its direct ancestor?

Why does an absolutely positioned element inherit its positioning from its closest absolutely positioned parent, not its direct ancestor?

Susan Sarandon
Susan SarandonOriginal
2024-10-29 00:49:30288browse

Why does an absolutely positioned element inherit its positioning from its closest absolutely positioned parent, not its direct ancestor?

Absolute Positioning Nested within Absolute Positioning

Within a web document, elements can be positioned using the CSS position property. When set to relative, an element is positioned relatively to its normal position, while absolute positions an element absolutely relative to its nearest positioned ancestor.

In the provided scenario, there are three div elements:

<code class="html"><div id="1st">
  <div id="2nd">
    <div id="3rd"></div>
  </div>
</div></code>
  • #1st has position: relative.
  • #2nd is absolutely positioned relative to #1st.
  • #3rd is absolutely positioned relative to #2nd.

The question arises: why is #3rd absolutely positioned relative to #2nd instead of its direct ancestor #1st?

The answer lies in the behavior of absolute positioning. When an element is absolutely positioned, it resets the position of its children. In this case, #2nd is absolutely positioned relative to #1st, so any children of #2nd (including #3rd) are absolutely positioned relative to #2nd. This behavior is intentional and cannot be bypassed.

To achieve absolute positioning relative to the outermost div (#1st), #3rd must be made a direct child of #1st:

<code class="html"><div id="1st">
  <div id="3rd"></div>
</div></code>

This arrangement ensures that #3rd is absolutely positioned relative to its nearest positioned ancestor, which is #1st.

The above is the detailed content of Why does an absolutely positioned element inherit its positioning from its closest absolutely positioned parent, not its direct ancestor?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn