What is a Block Formatting Context?
CSSThe short answer
A Block Formatting Context (BFC) is an independent layout region where elements are positioned according to their own rules, isolated from the rest of the page. It prevents margin collapsing between parent and child, contains floated elements, and stops elements from overlapping floats. Understanding BFC explains many "weird" CSS behaviors.
What creates a BFC
Several CSS properties trigger a new BFC:
overflow: hidden(orauto,scroll) — most commonly useddisplay: flow-root— designed specifically for creating a BFCdisplay: flexordisplay: grid— on the containerfloat: leftorfloat: rightposition: absoluteorposition: fixed
Problem 1: Containing floats
A container with only floated children collapses to zero height:
<div class="container"> <div style="float: left; width: 100px; height: 100px; background: red;" ></div></div><!-- container has 0 height -->Creating a BFC on the container fixes this:
.container { display: flow-root; /* creates BFC, contains the float */}display: flow-root was added specifically for this purpose — it creates a BFC without side effects.
Problem 2: Margin collapsing
Normally, parent and child margins collapse:
.parent { margin-top: 20px;}.child { margin-top: 30px;}/* Result: 30px gap above parent, not 50px */A BFC on the parent prevents this:
.parent { overflow: hidden; /* BFC prevents margin collapse */ margin-top: 20px;}.child { margin-top: 30px;}/* Result: 20px above parent + 30px inside parent */Problem 3: Preventing float overlap
Without a BFC, text wraps around floats. Sometimes you want a sibling element to sit beside a float without wrapping:
.sidebar { float: left; width: 200px;}.main { overflow: hidden; /* BFC — sits beside the float, no overlap */}The BFC on .main makes it respect the float's boundary instead of flowing under it.
display: flow-root
This is the modern, clean way to create a BFC:
.container { display: flow-root;}Before flow-root, developers used overflow: hidden which could clip content, or overflow: auto which could add scrollbars. flow-root has no side effects.
Interview Tip
BFC is an advanced CSS topic. Explain it as a "layout boundary" — elements inside a BFC do not affect elements outside it. The three use cases to know are: containing floats, preventing margin collapse, and preventing float overlap. Mention display: flow-root as the modern solution.
Why interviewers ask this
This is a deep CSS question that tests if you understand how the browser's layout engine works. Many CSS "bugs" are actually expected BFC behavior. A candidate who can explain BFC shows they understand CSS at a fundamental level, not just how to use properties.