Home >Web Front-end >CSS Tutorial >How Does CSS z-index Control the Stacking Order of HTML Elements?

How Does CSS z-index Control the Stacking Order of HTML Elements?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-25 03:47:11132browse

How Does CSS z-index Control the Stacking Order of HTML Elements?

Understanding z-index Stacking Order

Positioning Elements with z-index

The z-index property in CSS determines the stacking order of positioned elements. Specifically, it dictates which elements appear in front of or behind others on the z-axis, which represents depth on a three-dimensional plane.

Effects on Positioned Elements

Z-index only works on elements with a position other than static (i.e., absolute, relative, fixed, or sticky). It does not affect elements with a position of static or elements positioned using floats.

Stacking Contexts

A stacking context is created when an element is positioned and has a z-index applied. Within a stacking context, the z-index property sets the stacking order of the positioned element and its descendants. Stacking contexts prevent elements in one context from interfering with the stacking order of elements in a different context.

Stacking Order Rules

The stacking order of elements without a z-index specified is as follows:

  1. Backgrounds and borders of the root element
  2. Non-positioned, non-floating block elements
  3. Non-positioned floating elements
  4. Inline elements
  5. Positioned elements

When a z-index property is applied, the stacking order is modified:

  1. Backgrounds and borders of the root element
  2. Positioned elements with a z-index of less than 0
  3. Non-positioned, non-floating block elements
  4. Non-positioned floating elements
  5. Inline elements
  6. Positioned elements with a z-index of 0
  7. Positioned elements with a z-index greater than 0

Examples of Stacking Order

Mixed Sibling

s with and without Position:

  • div.sibling-1 has position: static and z-index: 0
  • div.sibling-2 has position: absolute and z-index: 1

Result: div.sibling-2 will appear in front of div.sibling-1 because its z-index is higher.

Nested

s with Sibling
s:

  • div.container has position: static and z-index: 0

    • div.child-1 has position: static and z-index: 0
    • div.child-2 has position: absolute and z-index: 1
  • div.sibling has position: relative and z-index: 2

Result: div.sibling will appear in front of both child divs because it is positioned with a higher z-index in a different stacking context.

The above is the detailed content of How Does CSS z-index Control the Stacking Order of HTML Elements?. 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