Block Formatting Context (BFC)
A Block Formatting Context (BFC) is an isolated layout compartment. Boxes inside a BFC never collapse vertical margins with the outside world, never overlap external floats, and expand their parent's auto height to enclose floated children.
BFC Float Enclosure & Margin Collapse Simulator
Toggle display: flow-root to observe float containment and margin isolation.
Under the Hood
In the layout engine, a Block Formatting Context (BFC) partitions the LayoutTree into a self-contained block-flow region with its own float exclusion space and margin-collapsing boundary. Inside that sealed compartment, floats and vertical margins cannot leak outward, and external floats cannot intrude.
- Margin Isolation: Normally, adjacent vertical margins between a parent and its first child collapse into a single margin. Establishing a BFC stops that collapse at the container edge.
- Float Enclosure: During Render Tree & Layout, each BFC tracks its own float exclusion space, forcing
height: autoto wrap floated descendants. - Clean Creation:
display: flow-rootcreates a BFC with zero clipping or scrollbar side effects, unlikeoverflow: hidden.
/* Clean BFC without clipping shadows or tooltips */
.media-card {
display: flow-root;
}
.media-card > img {
float: inline-start;
margin-inline-end: 1rem;
}Compare this with CSS Containment (contain: layout), which also establishes a BFC while additionally blocking layout invalidation walks, and CSS Logical Properties, which map block and inline axes to the document writing mode.
Problem Genealogy
- 1998–2015: Developers relied on
.clearfix::afterpseudo-elements oroverflow: hiddento contain floats, accidentally clipping shadows and dropdowns. - 2017+:
display: flow-rootshipped specifically to create a side-effect-free BFC.
Production Pitfalls
- Accidental clipping with
overflow: hidden: Usingoverflow: hiddensolely for a BFC slices offbox-shadow, focus outlines, andposition: stickydescendants. - Unexpected margin collapse: A
margin-topon the first heading inside a<section>escapes above the section's background unless a BFC or padding intervenes.
- When not to use
display: flow-root: If the container already usesdisplay: flexordisplay: grid, its children already live inside flex/grid formatting contexts,flow-rootis redundant.
Connections & Logical Next Steps
Grid establishes a grid formatting context independent of block and float flow.
Logical axes map block and inline directions onto the document’s writing mode.
Flexbox replaces block flow with main/cross axis sizing inside a flex formatting context.
BFCs partition the Layout box tree into independent block-flow regions.
BFCs isolate vertical margin collapse and floats, whereas logical properties orient box edges to writing mode.