With the CSS there is a possibility of stacking multiple boxes (elements) on top of each other to achieve a certain visual effect or perhaps a functional one, for instance due an overflow of elements. This effect is achieved by using a property called z-index.
The letter "z" within z-index refers to the "z-axis". That is derived from the 3 dimensions each box on the screen is made of. These are horizontal position (x-axis), vertical position (y-axis) and dept (z-axis).
The z-index property contains following information:
- value: auto, <integer> or inherit;
- initial: auto;
- applies to: positioned elements;
- inherited: no;
- percentages: N/A;
- media: visual;
- computed value: as specified.
When the value integer is assigned the box establishes a new stacking context and the value represents its stack level. If the value auto is used then the stack level for that element will be "0" in that stacking context. The smaller the number the least priority in the stacking context the element has; the negative values are being allowed. In case of having boxes with the same stack level, the priority (front) will take the last rendered box.
The term stacking context refers to the order in which the elements are painted on the canvas. Any stacking context may have other stacking contexts (sub-levels).
These are the rules explaining how the layers are being visualized within a stacking context and in order back-to-front:
- the background and borders of the element forming the stacking context;
- the child stacking contexts with negative stack levels (most negative first);
- the in-flow, non-inline-level, non-positioned descendants;
- the non-positioned floats;
- the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks;
- the child stacking contexts with stack level 0 and the positioned descendants with stack level 0;
- the child stacking contexts with positive stack levels (least positive first).
Example of CSS stacking elements: