Clearing & Containing Floats

Clearing Floats

Clearing floats is accomplished using the clear property, which accepts a few different values: the most commonly used values being left, right, and both.

div {  clear: left;}

The left value will clear left floats, while the right value will clear right floats. The both value, however, will clear both left and right floats and is often the most ideal value.

If we use the clear property with the value of both on the <footer> element, we are able to clear the floats. It is important that this clear be applied to an element appearing after the floated elements, not before, to return the page to its normal flow.

footer {
  clear: both;
}

Containing Floats

Rather than clearing floats, another option is to contain the floats. The outcomes of containing floats versus those of clearing them are nearly the same; however, containing floats does help to ensure that all of our styles will be rendered properly.

To contain floats, the floated elements must reside within a parent element. The parent element will act as a container, leaving the flow of the document completely normal outside of it. The CSS for that parent element, represented by the group class below, is shown here:

.group:before,.group:after {  
content: "";  
display: table;}
.group:after {  
clear: both;}
.group {  clear: both; 
 *zoom: 1;}

More specifically, the :before and :after pseudo-elements, as mentioned in the Lesson 4 exercise, are dynamically generated elements above and below the element with the class of group. Those elements do not include any content and are displayed as table-level elements, much like block-level elements. The dynamically generated element after the element with the class of group is clearing the floats within the element with the class of group, much like the clear from before. And lastly, the element with the class of group itself also clears any floats that may appear above it, in case a left or right float may exist. It also includes a little trickery to get older browsers to play nicely.

It is more code than the clear: both; declaration alone, but it can prove to be quite useful.

Looking at our two-column page layout from before, we could wrap the <section> and <aside> elements with a parent element. That parent element then needs to contain the floats within itself. The code would look like this:

<header>...</header><div class="group"> 
 <section>...</section>  
 <aside>...</aside>
 </div>
 <footer>...</footer>
.group:before,.group:after { 
 content: "";  
 display: table;}
 .group:after {  
 clear: both;}
 .group {  
 clear: both;  
 *zoom: 1;}
 section {  
 float: left; 
  margin: 0 1.5%;  
  width: 63%;}
  aside {  
  float: right; 
   margin: 0 1.5%;  
   width: 30%;
   }

Last updated