The Natural Stacking OrderIn an HTML page, the natural stacking order (i.e. the order of elements on the Z axis) is determined by a number of factors. Below is a list showing the order that items fit into a stacking context, starting with the bottom of the stack. This list assumes none of the items has
- Background and borders of the element that establish stacking context
- Elements with negative stacking contexts, in order of appearance
- Non-positioned, non-floated, block-level elements, in order of appearance
- Non-positioned, floated elements, in order of appearance
- Inline elements, in order of appearance
- Positioned elements, in order of appearance
z-indexproperty, when applied correctly, can change this natural stacking order.
Of course, the stacking order of elements is not evident unless elements are positioned to overlap one another. Thus, to see the natural stacking order, negative margins can be used as shown below:
The boxes above are given different background and border colors, and the last two are indented and given negative top margins so you can see the natural stacking order. The grey box appears first in the markup, the blue box second, and the gold box third. The applied negative margins clearly demonstrate this fact. These elements do not have
z-indexvalues set; their stacking order is the natural, or default, order. The overlaps that occur are due to the negative margins.
Why Does it Cause Confusion?
z-indexis not a difficult property to understand, due to false assumptions it can cause confusion for beginning developers. This confusion occurs because
z-indexwill only work on an element whose
positionproperty has been explicitly set to