CSS Containing Floats

A common float issue is the “containing floats” problem.

What happens is the browser removes floats from the normal document flow, i.e., the container no longer contains the floated items. The browser cannot determine the container’s height and can’t render the container correctly, because the rendering engine no longer cares about them.

Main Content

Sidebar Content

There are two main ways to palliate to this problem, both with advantages and inconveniences.

Overflow

overflow: hidden (or overflow: auto) is the simplest way to clear a floated element. overflow creates a block formatting context which contains everything inside the element to which it applies, including floats.

Main Content

Sidebar Content

Clearfix

Another solution is to use a clearfix: a standard pattern that developers use to ensure container doesn’t lose its floated children elements. It uses an invisible block element as the last child element, as well as the clear property.

Main Content

Sidebar Content

A clearfix uses the ::after pseudo-element with the following properties:

  • display: block;: make the content a block object
  • clear: both;: “clear” the bloats inside the container (force the invisible child directly below the floated content)
  • content: "";: set the content of the child element to empty string