← Lessons

quiz vs the machine

Silver1050

Frontend

The Box Model and Stacking Contexts

Every element is a box, and z order is governed by stacking contexts, not raw z index.

4 min read · intro · beat Silver to climb

Every element is a box

The CSS box model wraps each element in four layers, from inside out.

  • Content: the text or image, sized by width and height.
  • Padding: clear space inside the border, part of the background.
  • Border: the visible edge around the padding.
  • Margin: transparent space pushing other boxes away.

By default width measures only content. Setting box sizing border box makes width include padding and border, which makes layouts far easier to reason about.

Stacking contexts

Overlap is not decided by z index alone. A stacking context is a self contained layer. Inside it, children stack by z index, but the whole context stacks as one unit against its siblings.

  • The root element forms the base context.
  • A positioned element with a z index forms a new context.
  • Properties like opacity below one, transform, and filter also create one.

A child can never escape its parent context, so a high z index inside a low context still sits below an unrelated higher context.

Key idea

Set box sizing border box for predictable widths, and remember z index only ranks siblings within the same stacking context.

Check yourself

Answer to earn rating on the learn ladder.

1. With box sizing border box, what does the width property include?

2. Why might a child with z index 9999 still appear behind another element?

3. Which property creates a new stacking context?