Comm 328 Responsive Web Design

Clearing and Containing Floats

When using floats for layouts, elements are taken out of the document flow. This can cause two primary undesirable behaviors:

  • Elements after the float sneak up in the document
  • Container no longer contains floated elements

Clearing Floats

This is necessary when you want an element after a floated element to sit below the float. For an example, see the 2 column layout demo. The footer should sit below both the sidebar and main content.

To clear a float, add the clear property to the element that needs to clear the float. This is usually the element after the floated element.

The clear property can take the values of left, right, and both. Usually you'll want to use both.
footer {
  clear: both;
}

Containing Floats

When all of an elements children have been set to float, the element behaves as if it has no children. This means it has no content and therefore, a hight of 0. While sometimes this does not present a problem, you may notice it if the parent element has a set background color.


Containing Floats Example #1

In the following example, I have two circles inside a containing block with an aqua background.


Containing Floats Example #2

When I float both circles to the left, the containing block disappears. All of the children of the container have been taken out of the document flow by the floats.


Containing Floats Example #3

A simple way to fix this issue is to add the overflow property. This causes the parent to contain the children.

This approach won't always work however. A more robust method is to use what's known as the "clearfix". This uses the pseudo-element selectors to cause the parent to contain the float.

The clearfix is designed to be used as a class. You add this declaration in your stylesheet:
.clearfix:after {
  content:"";
  display:block;
  clear:both;
 }
Then you simply apply to class to the element you want to contain the floats.
<div class="blue clearfix">
  <div class="circle green"></div>
  <div class="circle red"></div>
</div>

The results look the same, but are generally more robust. The clearfix trick is ubiquitous on most grid based layouts.

While the clearfix often uses a class named 'clearfix', some people prefer to use a more semantic name such as 'container' or 'group'. Any of these choices are generally acceptable.