How does the z-index property really work?

Both negative and positive integers are allowed.

The position must be set on the element.

Before I get into those details, though, let me explain z-index from the ground up.

Every webpage is made up of what are called stacking contexts. You can think of these as, quite literally, a stack of elements. The z-index property determines the order of items in each stack, with higher z-index being placed further up.

All pages begin with a root stacking context, which builds from the root element (as you’d expect). But more stacking contexts can be created in a number of ways. One way is an absolutely positioned div; its children will be in a new stacking context.

The specs lists all of the instances that create a new stacking context. As others have stated, this includes explicitly positioned elements and will soon include elements that aren’t completely opaque.

As I said before, z-index only takes effect if you explicitly set the position of the element. This means setting it to be fixed, absolute, or relative. This is best shown through example, I think.

In this example, we’d expect the blue div to be on top of the grey one given its z-index, right? But, as you can see, it’s on the bottom. This is, of course, because we haven’t set its position. Once we do that it displays as we’d expect. Again, you must set the position.

The specs also tell us that negative values are fine. With that said, you don’t need to use negative values. It’s perfectly fine to use positive integers, too. The default z-index value for an element is 0.

For the record, w3schools is a notoriously unreliable source for learning. While it can be a quick and convenient resource, there are lots of gaps in their information, and at times even wrong information. I recommend you to use more reliable sources like the Mozilla Developer Network, and also the specs themselves.

Leave a Comment