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.