Home > Web Front-end > CSS Tutorial > How Does `position: relative;` Impact Z-Index and Element Stacking Order?

How Does `position: relative;` Impact Z-Index and Element Stacking Order?

Patricia Arquette
Release: 2024-12-24 08:41:14
Original
518 people have browsed it

How Does `position: relative;` Impact Z-Index and Element Stacking Order?

Why Does position: relative; Affect Z-Index?

Unexpectedly, setting position: relative; on an element can appear to change its z-index. This occurs due to the order of the stacking context, known as the painting order.

Standard Painting Order

Without position: relative;, an element is painted at the fourth step in the order:

  1. Root element
  2. Inline, non-positioned descendants
  3. Inline-block descendants
  4. In-flow, non-positioned, block-level descendants

Painting with position: relative;

Adding position: relative; to an element makes it positioned, so it is now painted at the eighth step along with other positioned elements:

  1. Inline, non-positioned, inline-block descendants
  2. Inline, non-positioned descendants of positioned elements
  3. Positioned, non-text descendants of inline-block elements
  4. All positioned, opacity, or transform descendants in tree order (unless they are subject to the z-index order)

Since both the container and the mask are positioned in this case and no z-index is specified, the order of their painting is determined by the tree order. By default, the mask is placed after the container in the HTML, so it is painted later.

Why Text Is Hidden

Originally, without position: relative;, the title text is hidden behind the blue overlay because the mask is painted at a later step. However, when position: relative; is applied to the container, it becomes positioned and is therefore also painted at step eight. Since the container is placed before the mask in the HTML and they both have no specified z-index, the container is painted first, causing the text to appear on top of the mask.

The above is the detailed content of How Does `position: relative;` Impact Z-Index and Element Stacking Order?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template