Home >Web Front-end >CSS Tutorial >Why Does `position: relative` Seem to Affect the Stacking Order Like `z-index`?

Why Does `position: relative` Seem to Affect the Stacking Order Like `z-index`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-25 00:11:15373browse

Why Does `position: relative` Seem to Affect the Stacking Order Like `z-index`?

Why Your Code Exhibits Z-Index-Like Behavior

In your markup, the .container element has position: relative, which you noticed seemingly mimics the effect of z-index. This behavior stems from the CSS painting order.

Painting Order and Positioning

The CSS specification dictates the order in which layers are painted on the screen. Without position: relative, your .container element is "in-flow" and painted in step 4 of the painting order.

Conversely, when you add position: relative, the .container becomes "positioned" and falls under step 8 of the painting order.

Tree Order Painting

Within each painting step, elements are painted in "tree order." In your case, both the .container and .mask elements are positioned elements. Since neither has an explicit z-index value, the tree order determines which is painted on top.

Reordering the Elements

In your initial markup, the .mask element appears after the .container in the hierarchy. Therefore, when both elements become positioned, the .mask is painted last, covering the .container.

However, if you reorder the elements so that .container is after .mask, both elements will be painted under step 8, still in tree order. In this scenario, .container will be painted last, removing the "z-index behavior" you observed earlier.

The above is the detailed content of Why Does `position: relative` Seem to Affect the Stacking Order Like `z-index`?. 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