The CSS z-index property often trips up both new and experienced developers. The aim of this article is to boil down a somewhat-complex specification to three major points, which should ease most z-index pain.
There has to be a position property
This is problem number one, and fixes most issues with z-index. If an element doesn't have a position property, such as
or whatever, any z-index value is ignored.
The default value of the position property is
static, and static elements don't have a z-index value, beyond the order in which they're displayed.
So there has to be a position property.
There's something called the stacking order
The stacking order is simple, as long as you understand how it works. Block 1 and everything within it has a z-index, as does everything within block 2.
An element that has a higher z-index in block 2 doesn't appear above anything in block 1 if block 1 (as a whole) has a higher z-index. This probably needs an example.
See the Pen An example of z-index and stacking order by Steve Pear () on CodePen.
block-2 displays in front of everything in
Things that render get a z-index
Now for something that seems weird at first. Almost anything that renders content before it's displayed gets a z-index value, for example
transform. Normally this wouldn't be a problem, but could cause unexpected results, say, if you're expecting an element with an
opacity property to appear behind another element.
Latest & featured