BFC — Block Formatting Context in CSS

Much of the information in this article comes from MDN. You can go to the further reading section for more details.

What is BFC

A BFC(block formatting context) is a mini layout system on your page. Everything in the BFC will not interfere with the outer world.

It is worth mentioning that a Flex/Grid container element can create a Flex/Grid formatting context, which is very similar to a BFC except they cannot have floating child elements. However, using Flex and Grid can still solve external float and margin collapse problems.

How to create a BFC

There are multiple ways to create a BFC. Here are just some common methods.

  • The root element of the document.
  • Elements with display CSS property set to “flow-root”, which makes it similar to the root element of the document.
  • Elements with float CSS property that is not “none”.
  • Elements with position CSS property set to “absolute” or “fixed”.
  • Direct child elements of Flex/Grid container when themselves are not Flex, Grid, or Table container.
  • ……

What problems can BFC solve

Contain inner float

Internally floating elements will break away from the normal document flow. As a result, the floating elements will not be wrapped by their parent element.

Making the container to be a BFC can enable it to contain a float child element.

Exclude external float

As above, a floating element will break away from normal document flow and overlap with its sibling element. If will turn this sibling element into a BFC, they will not overlap again.

Prevent margin collapse

Sometimes the top and bottom margin of two elements will collapse into a single margin. Making these two elements into different BFC can prevent margin collapse.

A front-end developer who likes designing stuffs. Technical blog rookie. Loving sharing.