Skip to main content

The CSS z-index Property

The z-index property sets the stack order of positioned elements, which decides whether an element sits in front of or behind others.

When elements are positioned, they can overlap. An element can have a positive or negative stack order.

Note: z-index only works on positioned elements (position set to absolute, relative, fixed, or sticky) and on flex items.

Example

A box with z-index: -1 is placed behind the text.

Prompt
An HTML page showing an element placed behind text with a negative z-index. In an internal <style> block, position a colored box absolutely at top-left with z-index -1 (stand-in for an image), so it sits behind the text. Add a heading and a paragraph on top of it.
Output: complete HTML page

Another z-index Example

A positioned element with a higher stack order is always in front of one with a lower stack order.

Example

Three overlapping boxes are stacked by their z-index: the gray box (3) is on top, then the green box (2), then the black box (1).

Prompt
An HTML page showing how z-index controls the stacking order of overlapping boxes. In an internal <style> block, make a relative container with three overlapping boxes: a black-box (z-index 1), a gray-box (z-index 3), and a green-box (z-index 2), each positioned so they overlap. The higher z-index appears on top. Add the three boxes inside the container.
Output: complete HTML page

Without z-index

If overlapping positioned elements have no z-index, they stack in the order they appear in the HTML source: later elements are drawn on top.

Example

The same boxes with no z-index stack in source order.

Prompt
An HTML page showing overlapping boxes with no z-index set. In an internal <style> block, make a relative container with three overlapping boxes (black-box, gray-box, green-box) with no z-index, positioned so they overlap. Without z-index, they stack in the order they appear in the HTML. Add the three boxes inside the container.
Output: complete HTML page

CSS Property

The property covered on this page is z-index, which sets the stack order of a positioned element.