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).

Z-index property

The z-index property contains following information:

  1. value: auto, <integer> or inherit;
  2. initial: auto;
  3. applies to: positioned elements;
  4. inherited: no;
  5. percentages: N/A;
  6. media: visual;
  7. 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:

  1. the background and borders of the element forming the stacking context;
  2. the child stacking contexts with negative stack levels (most negative first);
  3. the in-flow, non-inline-level, non-positioned descendants;
  4. the non-positioned floats;
  5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks;
  6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0;
  7. the child stacking contexts with positive stack levels (least positive first).

Example

Example of CSS stacking elements:

 

›› go to examples ››