CSS & LayoutBaseline · Widely

Block Formatting Context (BFC)

Mental Model

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.

Interactive Simulator

BFC Float Enclosure & Margin Collapse Simulator

Toggle display: flow-root to observe float containment and margin isolation.

Parameter Profile
flowRootOff
floatChild120
childMarginTop24
flowRoot
Off
floatChild
120
childMarginTop
24
Parameters evaluated in real time.

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.

  1. 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.
  2. Float Enclosure: During Render Tree & Layout, each BFC tracks its own float exclusion space, forcing height: auto to wrap floated descendants.
  3. Clean Creation: display: flow-root creates a BFC with zero clipping or scrollbar side effects, unlike overflow: hidden.
CSS
/* 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::after pseudo-elements or overflow: hidden to contain floats, accidentally clipping shadows and dropdowns.
  • 2017+: display: flow-root shipped specifically to create a side-effect-free BFC.

Production Pitfalls

Production Pitfall
  • Accidental clipping with overflow: hidden: Using overflow: hidden solely for a BFC slices off box-shadow, focus outlines, and position: sticky descendants.
  • Unexpected margin collapse: A margin-top on the first heading inside a <section> escapes above the section's background unless a BFC or padding intervenes.
When Not to Use
  • When not to use display: flow-root: If the container already uses display: flex or display: grid, its children already live inside flex/grid formatting contexts, flow-root is redundant.

Connections & Logical Next Steps

Mechanical Comparisons