CodeBlanks Logo Icon CodeBlanks

Z-index

CSS course · Beginner · Lesson 74/82

Learn element stacking with z-index.

Stacking order: z-index

Elements on a page can overlap — a notice box on top of content, a menu over a heading. The CSS z-index property decides which one sits on top and which one stays behind.

z-index works only on positioned elements, that is, ones whose position is not static. The larger the value, the higher the element sits. For example, z-index: 10 appears above z-index: 5.

Stacking context

When an element takes a z-index along with a position, it creates a new stacking context. Children inside this context cannot compete directly with outside elements; the context as a whole is ordered first within the outer context.

That is why a child with z-index: 9999 inside a modal whose own z-index: 1 may still sit below an outside element with z-index: 5. The context boundary beats the inner value.

Exercise Bring the notice to the top

Write a .notice class selector. Inside it, add both position: fixed and z-index: 100. The notice will stay fixed on screen and appear above other elements.

Show example solution
/* bring the notice forward */
.notice {
  position: fixed;
  z-index: 100;
}

Test yourself

  1. On which element does z-index take effect?

    .a { position: static; z-index: 5; }
    .b { position: fixed; z-index: 2; }
    • Only on .a (z-index is larger)
    • Only on static elements
    • Only on .b (position is not static)
    • Equally on both
    Show answer

    Only on .b (position is not static) — Correct. z-index takes effect only on .b because its position is not static.

  2. Bring the notice forward

    .notice {
      position: relative;
      ____;
    }
    Show answer
    .notice {
      position: relative;
      z-index: 10;
    }
  3. Match the z-index value to its position

    z-index: 100
    Topmost
    z-index: 5
    Middle
    z-index: 0
    Default level
    z-index: -1
    Background

All lessons in Beginner