Abdullah Al Numan
Posted on June 21, 2022
Block Formatting Context is a type of CSS formatting context. It is set by the values of type for outer and inner displays of a block element.
For example,
.some-class {
display: inline-block;
}
The outer display type determines the rules for the element's participation in the Flow Layout and the inner type sets the layout rules for its children.
There are numerous ways a Block Formatting Context is formed. And BFCs can be created for serving various purposes while creating CSS layouts. We'll point out some commonly used examples below.
The Initial Block Formatting Context
For an HTML document, the first Block Formatting Context is established by the <html>
element itself. It is called the Initial Block Formatting Context and it sets the default flow layout of the document to be composed of block and inline elements. The flow layout is also called the Normal Flow. So, an HTML document begins with having a Block Formatting Context -- with its content following the normal flow. And the normal flow allows its content to have any or both of Block and Inline Formatting contexts.
With Out-of-flow Elements
A Block Formatting Context is created when an element is made to move out of normal flow. This is typically done when position
of the element is set to absolute
or fixed
, or when an element is floated.
.some-class {
position: absolute;
}
p { float: left; }
With any of these rules, the element is moved out of flow of the document and it forms its own BFC.
Floating an element comes with the risk of collapsing margins and disrupting a layout. So, it should be contained within the layout by creating a new Block Formatting Context in its parent element. There are various ways of achieving this. One involves using display: flow-root
, as mentioned below.
With display: flow-root;
Using display: flow-root
creates a new Block Formatting Context. This is especially useful for clearing a float and keeping it inside its container, eventually keeping it in-flow.
Floating an element itself creates a BFC that disrupts the layout of the container. So, setting the display
value of the floating element's container to flow-root
creates a BFC, similar to the one at <html>
, the root. This makes the float follow normal flow.
There are many other instances when a BFC can form, and they are worth considering individually because of their broader scopes and usage. For example, when overflow
value is set to anything other than visible
and clip
. And when display
is flex
or grid
or any table-*
values, etc.
References
Posted on June 21, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.