Encodera

Thanks for reading!

Donate to the site — we work hard for you.

HTML & CSS reference

z-index

Which positioned element is drawn on top when they overlap.

Syntax

z-index: number;

Values

ParameterTypeDescription
numberintegerA larger number is drawn above a smaller one; it can be negative.
autokeywordThe order of the elements in the markup (the default).

Examples

The first block is on top although the second comes later:

<style>
  .box { position: relative; width: 120px; height: 70px; padding: 6px; color: white; }
  .a { background: royalblue; z-index: 2; }
  .b { background: crimson; margin: -40px 0 0 40px; z-index: 1; }
</style>
 
<div class="box a">z-index: 2 — on top</div>
<div class="box b">z-index: 1</div>

Notes

z-index works on positioned elements and on flex and grid items. Elements are compared only within the same stacking context: a child with z-index: 9999 cannot rise above the neighbor of its parent if the parent itself is lower. Contexts are also created by opacity below 1, transform and filter.

See also

  • position — How an element is positioned: in the normal flow or by offsets.
  • opacity — The transparency of the whole element together with its content.

Related recipes

In the tutorial

  • Overflow and layers — What to do when content does not fit into a block — overflow, scrolling, an ellipsis — and how z-index decides which element lies on top.

Thanks for reading!

Donate to the site — we work hard for you.