The CSS z-index property

By

Published · Updated

Tagged: CSS

Learn how the CSS z-index property controls which overlapping elements appear on top, why higher values sit nearer users, and when it applies to positioned, flex and grid items.

In the positioning post I mentioned that you can use the z-index property to control the Z axis positioning of elements.

It’s very useful when you have multiple elements that overlap each other, and you need to decide which one is visible, as nearer to the user, and which one(s) should be hidden behind it.

This property takes a number (without decimals) and uses that number to calculate which elements appear nearer to the user, in the Z axis.

The higher the z-index value, the more an element is positioned nearer to the user.

When deciding which element should be visible and which one should be positioned behind it, the browser does a calculation on the z-index value.

The default value is auto, a special keyword. Using auto, the Z axis order is determined by the position of the HTML element in the page - the last sibling appears first, as it’s defined last.

By default elements have the static value for the position property. On a normal box, z-index does nothing unless position is absolute, relative, fixed or sticky. It also works on flex items and grid items even with position: static.

A z-index other than auto on a positioned element creates a stacking context. So do things like opacity below 1, transform, filter, and isolation: isolate. Children cannot escape their parent’s context. That is why z-index: 9999 sometimes does nothing: the parent already locked them in. MDN’s stacking context guide has the full list.

Example:

.my-first-div {
	position: absolute;
	top: 0;
	left: 0;
	width: 600px;
	height: 600px;
	z-index: 10;
}

.my-second-div {
	position: absolute;
	top: 0;
	left: 0;
	width: 500px;
	height: 500px;
	z-index: 20;
}

The element with class .my-second-div will be displayed, and behind it .my-first-div.

Here we used 10 and 20, but you can use any number. Negative numbers too. It’s common to pick non-consecutive numbers, so you can position elements in the middle. If you use consecutive numbers instead, you would need to re-calculate the z-index of each element involved in the positioning.

Want me to talk about your product? You can sponsor this site.

Related posts about css: