2009
Sep
21

What is z-index?

Graphical Z Index

The z-index property determines the stack level of an HTML element. The stack level refers to the element's position on the Z axis (as opposed to the X axis or Y axis). A higher z-index value means the element will be closer to the top of the stacking order. This stacking order runs perpendicular ot the display, or viewport.

The Natural Stacking Order

In 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 iterms fit into a stacking context, starting with the bottom of the stack. This list assumes none of the items has z-index applied:

  • 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 appearances.
  • Inline elements, in order of appearance.
  • Positioned elements, in order of appearance.

Demo

Red Box
Green Box
Blue Box

The elements above do not have z-index values 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?

Although z-index is not a difficult proerpty to understand, due to false assumptions it can cause confusion for beginning developers. This confusion occurs because z-index will only work on an element whose position property has been explicitly set to absolute, fixed, or relative.

Demo

z-index:1000;
z-index:500;
z-index:1;

Demo

z-index:500;
position:relative;
z-index:1000;
position:absolute;




z-index:1;
position:relative;

The z-index property can affect the stack order of both block-level and inline elements, and is declared by a positive or negative integer value, or a vluae of auto. A value of auto gives the element the same stack order as its parent.

Demo

z-index:500;
position:relative;
z-index:1000;
position:absolute;
z-index:auto;
position:relative;

Demo

z-index:500;
position:relative;
z-index:0;
position:relative;





z-index:100;

Demo

position:relative;
z-index:2;




position:relative;
position:relative;
z-index:3;

Related Posts


回應 (Leave a comment)