Describe Block Formatting Context (BFC) and how it works.
TL;DR
A block formatting context (BFC) is an independent region for normal-flow block layout and float interaction. A new BFC contains its internal floats, prevents external floats from intruding into it, and stops certain vertical margins from collapsing across its boundary. When the goal is to create a BFC intentionally, display: flow-root communicates that intent without clipping content or creating scrollbars.
.media-object {display: flow-root;}.media-object > img {float: inline-start;margin-inline-end: 1rem;}
Describe Block Formatting Context (BFC) and how it works.
A BFC defines where block boxes participate in flow layout and how floats affect nearby content. It is a layout boundary, not a visible element or a new DOM subtree.
Why a BFC matters
Creating a BFC can:
- Make a container's height include floated descendants.
- Keep a normal-flow box from wrapping around a neighboring float.
- Prevent a descendant's vertical margin from collapsing through the container boundary.
Common ways a BFC is created
The full list is longer, but common triggers include:
- The root
<html>element. - A floated element.
- An absolutely or fixed-positioned element.
display: inline-block,table-cell, ortable-caption.display: flow-root.- A block with
overflowother thanvisibleorclip. - Certain containment and container-query settings.
Flex and Grid containers establish their own flex and grid formatting contexts. They have some similar boundary effects, but describing them simply as BFCs hides important differences, such as how their children are laid out.
Prefer an intentional trigger
Older code often uses overflow: hidden or overflow: auto solely to contain floats. That creates a BFC, but it may clip shadows or produce unwanted scrolling. display: flow-root states the layout intention directly and avoids those overflow side effects.
In DevTools, inspect the computed display, float, position, overflow, contain, and container-type values when a float escapes a parent or margins collapse unexpectedly.