tezvyn:

What is a CSS containing block?

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

how percentages and offsets are resolved in layout.

OUTLINE

containing block is the reference rectangle; static and relative use the nearest block ancestor's content box, absolute uses nearest positioned ancestor, fixed uses the viewport.

WHAT THIS TESTS This probes whether you truly understand how layout math is anchored. The containing block is the rectangle that percentage widths, heights, and the top/right/bottom/left offsets are resolved against. Misunderstanding it leads to absolutely positioned elements landing in unexpected places.

A GOOD ANSWER COVERS Define the containing block as the reference box for computing percentages and inset offsets. For static and relative elements, the containing block is the content box of the nearest block-level ancestor (in normal flow). For absolutely positioned elements, it is the padding box of the nearest ancestor whose position is not static; if none exists, it is the initial containing block tied to the viewport. For fixed elements, it is normally the viewport, so they stay put during scroll. The key twist: a transform, filter, perspective, will-change, or contain on an ancestor establishes a new containing block, which can capture even fixed-positioned descendants.

COMMON WRONG ANSWERS Saying the containing block is always the direct parent. Forgetting that absolute positioning ignores non-positioned ancestors and walks up to the nearest positioned one. Not knowing that transforms on an ancestor break fixed positioning relative to the viewport.

LIKELY FOLLOW-UPS Why does adding transform to a parent suddenly anchor a fixed child to that parent? How does percentage height behave when the containing block has no explicit height? What box (content versus padding) is used for relative versus absolute? How does the initial containing block relate to the viewport?

ONE CONCRETE EXAMPLE You place a modal with position fixed and expect it pinned to the viewport, but it scrolls with a section. The cause: a parent has transform applied, creating a new containing block that the fixed element now resolves against. Removing the transform, or intentionally relying on it, restores or redefines the anchor.

Read the original → developer.mozilla.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.