Sub topic 12
Block formatting contexts and display: flow-root
This chapter assumes you know margin collapsing, the difference between block and inline display, and how float and overflow work at a basic level. Here you will learn what a block formatting context (BFC) is, which properties create one, and how display: flow-root gives you one without side effects.
What a block formatting context is
A block formatting context is a region of the page where block boxes are laid out by one self-contained set of rules. Inside it, boxes stack vertically, one after another, starting at the top of the region. The distance between neighbouring boxes comes from their margins. Each box's left outer edge touches the left edge of the region, and in a right-to-left language the right edge is used instead.
The page always has one BFC, created by the root <html> element. Other elements can start a new BFC inside it. The new BFC is a small independent layout region, and it isolates its contents from the outside layout in three ways:
- Floats stay inside. The BFC root grows tall enough to contain its floated descendants.
- Margins stay inside. Margins of the BFC root's children do not collapse with the root's own margins.
- Outside floats are avoided. The border box of a BFC root never overlaps a float that belongs to the surrounding context.
What creates a BFC
Many properties create a BFC. These are the common ones:
| Trigger | Side effect |
|---|---|
| `display: flow-root` | None. It exists only for this purpose. |
| `overflow` other than `visible` or `clip` (for example `hidden` or `auto`) | Clips content, and may add scrollbars. |
| `float` other than `none` | Shrinks the box to its content width and removes it from normal flow. |
| `position: absolute` or `fixed` | Removes the box from flow and shrinks its width. |
| `display: inline-block` or `table-cell` | Changes how the box sits in a line or table. |
| `contain: layout`, `content`, or `paint` | Also isolates layout and may clip painting. |
Flex and grid containers are a special case. They create a flex formatting context or grid formatting context for their children, not a BFC. Their rules are different. Their items are laid out by flex or grid algorithms, and their margins never collapse with each other or with the container. A flex or grid item also establishes an independent formatting context for its own contents, which behaves like a BFC for the purposes of this chapter.
Problem 1: a container that ignores its floats
A floated element is taken out of normal flow. A parent that contains only floated children therefore has no in-flow content, and its height collapses to zero (assuming no padding or border).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Float containment</title>
<style>
.container {
border: 3px solid #333;
background: #eef;
}
.thumb {
float: left;
width: 100px;
height: 100px;
background: tomato;
margin: 8px;
}
</style>
</head>
<body>
<div class="container">
<div class="thumb"></div>
<div class="thumb"></div>
</div>
<p>Next paragraph.</p>
</body>
</html>The container renders as a thin bar, just its two 3px borders, and the red squares hang out of the bottom. The paragraph also wraps around them. Adding one declaration to .container fixes this:
.container {
display: flow-root;
}The container is now a BFC root. To compute its auto height, a BFC root includes its floated descendants, so the container wraps both squares and the paragraph starts below it.
The older fixes
Before flow-root existed, developers got the same result in other ways. You will see them in older code.
overflow: hiddenoroverflow: autoon the container. This works, but it clips anything that extends past the box, such as box shadows, focus rings, and absolutely positioned popovers. Withautoyou can also get unexpected scrollbars.- The clearfix hack, which adds a cleared pseudo-element at the end of the container:
.clearfix::after {
content: "";
display: block;
clear: both;
}The clearfix has no side effects on clipping, but it adds a generated element and does not create a BFC. It therefore does not help with the margin and float-avoidance problems below.
Problem 2: margins that escape the container
Without a BFC, the top margin of a first child can collapse with the top margin of its parent when nothing separates them (no padding, border, or line box). The child's margin then "leaks" outside the parent, and the parent moves down instead of the child moving inside it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Margin escaping</title>
<style>
body { margin: 0; }
.container {
background: #dfd;
}
.container > h1 {
margin-top: 2rem;
}
</style>
</head>
<body>
<div class="container">
<h1>Title</h1>
</div>
</body>
</html>Here the green background starts 2rem below the top of the page, and the heading sits flush against the top of the green area. Add the fix:
.container {
display: flow-root;
}Now the h1 margin stays inside the container. The green background starts at the top of the page, and the 2rem gap appears inside it, above the heading. The same applies to the bottom margin of the last child.
Two points limit what a BFC does here:
- Margins between siblings inside the BFC still collapse. A BFC changes only the relationship between the root and its children.
- The BFC root's own margins can still collapse with its siblings in the surrounding context. The exception is a flex or grid item, whose margins never collapse.
Problem 3: text wrapping around a float
A normal block box ignores floats for its own box, but its line boxes shorten to make room. The block's background and border still run underneath the float, and only the text wraps. Making the block a BFC root changes that: the whole box avoids the float.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Side-by-side with a BFC</title>
<style>
.sidebar {
float: left;
width: 180px;
height: 120px;
background: #fc9;
}
.main {
background: #cde;
display: flow-root;
}
</style>
</head>
<body>
<div class="sidebar">Sidebar</div>
<div class="main">
<p>This text stays in a rectangle beside the sidebar. It does not wrap underneath it, even when it runs longer than the sidebar is tall.</p>
</div>
</body>
</html>With display: flow-root on .main, the blue box starts to the right of the sidebar and keeps a straight left edge for all its lines. Remove that declaration and the blue background stretches under the sidebar. Lines of text beside the sidebar are shortened, but lines below it return to the full width.
This was a common two-column layout technique before flexbox and grid. Today, use flex or grid for page columns. The BFC behaviour is still useful for media objects (an image floated beside text) where you want the text to form a clean column.
Choosing a trigger
Use this order of preference:
display: flow-rootwhen you only need a BFC. It has no side effects and says what you mean.- Flex or grid when you are building a layout, since you then get alignment and spacing control too.
overflow: hiddenorautoonly when you also want clipping or scrolling, so the side effect is intended.- Clearfix for legacy code or very old browsers.
display: flow-root is supported in current Chrome, Edge, Firefox, and Safari. Browsers older than about 2019 lack it. If you must support them, put overflow: hidden before it as a fallback, accepting the clipping.
Common errors
- Expecting a BFC to stop all collapsing. Sibling margins inside the BFC still collapse.
- Using
overflow: hiddenand losing a shadow or outline. The box clips whatever is painted outside it. Switch toflow-root. - Applying
flow-rootto the floated element itself. A float is already a BFC root. Putflow-rooton the parent that needs to contain it. - Using
flow-rooton a flex item to fix collapsing. Flex items never have collapsing margins, so there is nothing to fix. - Expecting
clearto behave the same.clearmoves a box below earlier floats. A BFC root instead sits beside them if there is room, and moves below only if it cannot fit.
Exercises
Exercise
A .card has background: white and contains one <h2> with margin-top: 24px. The card has no padding or border. In the browser, the white background starts 24px lower than expected and the heading touches the top of the white area. What causes this, and what one-line CSS fix keeps the gap inside the card without adding padding or clipping?
Show answer
The h2's top margin collapses with the card's top margin, because nothing separates them. The margin therefore moves the whole card down instead of sitting inside it. Adding display: flow-root to .card makes the card a block formatting context root, so the child's margin no longer collapses through its edge and the 24px gap appears inside the white area.
Exercise
You apply display: flow-root to a <ul> that contains two <li> elements, each with margin: 20px 0. Does the gap between the two items change from 20px to 40px? Explain.
Show answer
No. The gap stays 20px. Margins between siblings inside the same block formatting context still collapse to the larger of the two. A BFC root only stops collapsing between itself and its children. It does not stop collapsing between its children.
Exercise
Name two reasons to prefer display: flow-root over overflow: hidden for containing floats.
Show answer
flow-root has no side effects, while overflow: hidden clips content that extends outside the box, such as box shadows, focus outlines, and popovers. flow-root also states the intent clearly, and it does not risk unexpected scrollbars the way overflow: auto can.