How to Use and Clear the CSS float Property

Hero image for How to Use and Clear the CSS float Property. Image by Janis Fasel.
Hero image for 'How to Use and Clear the CSS float Property.' Image by Janis Fasel.

The CSS float property is a layout technique that allows an element to be placed alongside other elements, where text and inline elements will wrap around it. This can be used to create multicolumn layouts or to position elements alongside each other horizontally.

Here are a couple of examples of how to use the float property in a CSS rule:

.float-left {  float: left;}.float-right {  float: right;}

You can then apply these classes to HTML elements via the class names as you always would; like so:

<div class="float-left">  I will be floated to the left</div><div class="float-right">  I will be floated to the right</div>

The elements with the floatleft and floatright classes will be floated to the left and right, respectively, with text and inline elements wrapping around them, as you might see in a more fluid newspapertype layout.

The reason float can often cause confusion is the way that floated elements are removed from the 'normal' float of the document; they do not take up space within the layout as a nonfloated element would. This behaviour can lead to unintended consequences as it means that a parent element will collapse if it has no other nonfloated children.

To fix this, you can add a 'clearfix' to the parent element, which effectively adds nonfloated table elements to the beginning and end of the element, effectively enclosing the content and forcing the parent's height to stretch to include the floated children:

.clearfix::before,.clearfix::after {  content: '';  display: table;}.clearfix::after {  clear: both;}.clearfix {  zoom: 1;}

As before, this can then be applied to the parent element of the floated elements:

<section class="clearfix">  <div class="float-left">    I will be floated to the left  </div>  <div class="float-right">    I will be floated to the right  </div></section>

The Wrap‑Up

In CSS, float is a very versatile but often misunderstood (and perhaps flawed) way of laying out elements on the page. It is fair to say, that it might be showing its age: float has largely been superseded by newer layout techniques such as flexbox and grid, which offer more modern, powerful, and flexible layout options.

All that said however it is still widely used, you will inevitably come across it frequently in legacy codebases, and it's an important tool to have in your toolkit.


Categories:

  1. CSS
  2. Front‑End Development