Z-Index

Control the stacking order of elements on a page, determining which elements appear on top of others.

What is Z-Index?

The `z-index` property in CSS is used to control the vertical stacking order of elements that overlap. Think of the z-axis as a line coming out of the screen towards you. Elements with a higher `z-index` value are positioned "closer" to the user and will appear on top of elements with lower values.

It's important to remember that `z-index` only works on elements that have a defined `position` value other than `static` (the default). This means you must apply `position: relative;`, `position: absolute;`, `position: fixed;`, or `position: sticky;` for `z-index` to have any effect.

💡 Key Rule

Z-index is ignored for non-positioned elements. If you set `z-index: 100;` on a `div` with `position: static;`, it will have no effect on its stacking order.

Understanding Stacking Contexts

Elements are stacked based on their **stacking context**. A stacking context is a three-dimensional concept that is generated by an element that has a `position` value other than `static` and a `z-index` value other than `auto`.

The key takeaway is that `z-index` values are only compared within the same stacking context. An element with a `z-index` of 10 inside a container with a `z-index` of 1 will always be rendered below an element with a `z-index` of 2 that is in a different stacking context (or the root stacking context).

Live Example

In this example, three boxes are positioned to overlap. Notice how the box with the highest `z-index` value (`Box 3`) appears on top, while the box with the lowest value (`Box 1`) is at the bottom.

Z-Index in Action
Box 1
z-index: 1
Box 2
z-index: 2
Box 3
z-index: 3