Advanced

Positioning and stacking

Positioning takes an element out of the flow and stacking decides which painted last. Both are needed occasionally, and both fail in the same way: the element is somewhere you did not expect, and the reason is a container you forgot about.

What you will see

The badge now sits inside the card. The container is the whole answer.

About 1 min of reading

Try It

Anchor a badge to a card.

1

Without the anchor

.badge { position: absolute; top: 4px; right: 4px; }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The badge sits near the page corner - it found no positioned container.
2

Add the anchor

.card { position: relative; } .badge { position: absolute; top: 4px; right: 4px; }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The badge now sits inside the card. The container is the whole answer.

Data Flow

A container anchors, a number orders.
1 Set the container as the reference
↓
2 Position the child against it
↓
3 Paint order decides overlap
↓
4 Check the container's own context
Why this works
Take it out of the flow deliberately

An element removed from the flow leaves a gap where it was and no longer sizes its parent. That is why a page collapses when everything is absolute, and why the fix is usually flexbox instead.

Name the container

When a positioned child lands in the wrong place, the answer is which container it is positioning against. Setting relative on the intended one and checking is faster than reasoning about the whole page.

Examples

Relative is the anchor

A container set to relative becomes the reference for an absolutely positioned child. Without it, the child positions against the page, which is why a badge lands in the corner instead of on the card.

Stacking is per context

A high number inside a container that is itself low cannot rise above a sibling of that container. The number is not global, and finding the container that created the context is the fix.

Sticky needs a scroll

A sticky element stays put while its container scrolls and stops at the container's edge. If it never sticks, the container is probably not scrolling, which is the usual cause.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Pseudo classes and states
Previous Lesson
Pseudo classes and states
Next Lesson
Markup that serves everyone
Markup that serves everyone →