A block formatting context (BFC) is the layout environment for normal flow: block boxes stack one after another in the block direction, vertical margins between them collapse, and floats are positioned and wrapped around. The box that starts a new one is a BFC root, and it isolates what's inside from what's outside, in three ways:
- It contains its floats. An
autoheight grows to the bottom of its floating descendants, so a card with only a floated image doesn't collapse to0. - It doesn't overlap outside floats. Its border box sits beside a float in the same context and narrows to fit, instead of running underneath it.
- Margins don't collapse across its edge. A first child's
margin-topstays inside the root instead of leaking out through it.
What creates one:
- the root element;
display: flow-root: the purpose-built switch, with no other effect;- floats and absolutely or fixed positioned boxes;
- inline-blocks, table cells and captions, and
display: table; overflowother thanvisibleorclip, since it makes a scroll container;- flex and grid items, which always establish an independent formatting context;
- multi-column containers and
column-span: all; contain: layout,paint,contentorstrict, andcontainer-type: sizeorinline-size;align-contentother thannormalon a block container.
Things that don't: position: relative, transform, opacity, z-index, isolation (those affect stacking, not layout), overflow: clip, and padding or borders, which stop margin collapsing but don't contain floats.
The classic interview answer is "use overflow: hidden to clear floats". It works, but it also clips shadows and focus rings and creates a scroll container. display: flow-root is the modern answer.