Sobes.tech
Junior

What is z-index and how is it used in web development?

sobes.tech AI

Answer from AI

z-index is a CSS property that determines the stacking order of elements along the Z-axis. Elements with higher z-index values are displayed above those with lower values.

It is used to control the stacking depth of positioned elements (i.e., elements with a position property other than static): relative, absolute, fixed, sticky.

Key points of usage:

  • Static positioned elements (position: static;) do not participate in stacking contexts and ignore z-index.
  • The z-index value applies only to elements that create a new stacking context. Such a context is created, for example, when using position with values other than static, or applying certain other CSS rules (e.g., opacity < 1).
  • Within a stacking context, elements with higher z-index are placed above those with lower z-index.
  • Nested stacking contexts are stacked as a whole within the parent context.
  • Without an explicit z-index, the stacking order is determined by the order of elements in the DOM.

Example of usage:

.box1 {
  position: absolute;
  top: 10px;
  left: 10px;
  width: 100px;
  height: 100px;
  background-color: red;
  z-index: 2; /* Will be above .box2 */
}

.box2 {
  position: absolute;
  top: 30px;
  left: 30px;
  width: 100px;
  height: 100px;
  background-color: blue;
  z-index: 1; /* Will be below .box1 */
}