VOOZH about

URL: https://www.geeksforgeeks.org/css/describe-z-index-and-how-a-stacking-context-is-formed-in-css/

⇱ CSS Stacking Context and Z-Index - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSS Stacking Context and Z-Index

Last Updated : 19 Jan, 2026

The stacking order describes the order in which HTML elements are positioned. By default, HTML elements are positioned in the following order:

  • Root element(<html>)
  • Non-positioned elements in the order they're defined(elements with no position described, i.e., static)
  • Positioned elements in the order they are defined(elements with a position other than static)

Let us try to understand how the default stacking order works:

Example 1: Default stacking order

Output:

z-index: In order to change the stacking order, we can use z-index. Element with higher z-index is placed on top of the element with lower z-index. Let us use the same. An important thing to note is that in order to use z-index, elements should be positioned. To learn more about CSS, positions, refer this article.

Example 2: Stacking with z-index

We use the previous example, but this time we will apply a z-index value to the green and blue boxes.

Example 3: Now in order to understand stacking context, Let's say we add another box to the layout and we want the blue box to be behind it. 

Example 4: If we want to place blue box on top of orange box, there are two things that we can do:

  • Either make the blue box a child element of green box
  • Define orange box outside the green box

Here, we will make blue box a child element of green box.


Comment