Z-Index

z-index controls the stack order of elements.

  • Higher z-index = element appears on top
  • Lower z-index = element stays behind

Think like layers in Photoshop.

HTML/CSS/JS SandboxHTML Sandbox — click to edit

Important Rule

z-index only works when element has:

position: relative;
position: absolute;
position: fixed;
position: sticky;

Without position, z-index usually won't work.


Negative Z-Index

.bg{
  position:absolute;
  z-index:-1;
}

Used to send elements behind everything.


Stacking Context 

Sometimes z-index not working because of stacking context.

BOX 1 PARENT CHILDHTML Sandbox — click to edit