๐ŸŽ“ A1Learner
๐Ÿ”

CSS Z-Index

Z-index is a property that sets the stacking order of overlapping elements. The element with the higher z-index value paints on top.

The picture on top

Both elements are positioned, and a negative top margin pulls the table up. The picture has the higher value, so it paints over the table where they overlap.

.pic {
  position: relative;
  z-index: 2;
}
table {
  position: relative;
  z-index: 1;
  margin-top: -30px;
}

Swap the order

The same overlap with the values swapped puts the table on top. Only the numbers changed, and the winner changed with them.

.pic {
  position: relative;
  z-index: 1;
}
table {
  position: relative;
  z-index: 2;
  margin-top: -30px;
}

A third layer

The demo paragraph is pulled up over the bottom edge of the table. Its higher value paints it above the table.

table {
  position: relative;
  z-index: 1;
}
#demo {
  position: relative;
  z-index: 3;
  margin-top: -20px;
}

Example

.pic {
  position: relative;
  z-index: 2;
}
table {
  position: relative;
  z-index: 1;
  margin-top: -30px;
}
#demo {
  position: relative;
  z-index: 3;
  margin-top: -20px;
}

Key points

  • Z-index works only on positioned elements.
  • A positioned element has a position value other than static.
  • With auto values, elements stack in document order.
  • Document order is the order the elements appear in the HTML.
  • Negative z-index values place an element behind others.
  • Elements must overlap before stacking order can show.

In this example, the picture and the table are both positioned. The negative top margin pulls the table up over the bottom of the picture. The picture has the higher value of the pair, so it paints on top there. The demo paragraph is pulled up over the table, and its value of 3 puts it above both.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

Two positioned elements overlap. Which one paints on top?