Learn How to Use Float Property in CSS

Code Playground is only enabled on larger screen sizes.

Originally, the float property was used to take an HTML element (usually an image) out of the normal flow of the webpage and make it float on top of other elements.

But then developers quickly realized you can use float to design entire webpage layouts, so that multiple columns of information could sit next to each other.

However, with the creation of modern layout techniques such as grid and flexbox, float gradually returned to its original purpose.

Float

Here is an example of using float:

<h2>Lorem ipsum dolor sit</h2>

<div>Float</div>

<p>. . .</p>
<p>. . .</p>
<p>. . .</p>
<p>. . .</p>
div {
  float: left;
}

As you can see, the <div> element is taken out of the normal flow of the webpage, and it is now floating on top of the <p> element.

In this example, we are making the <div> box float to the left side. Similarly, you can make it float to the right side like this:

div {
  float: left;
  /* . . . */
}

You can also float multiple boxes together like this:

<h2>Lorem ipsum dolor sit</h2>

<div class="left">Float</div>
<div class="left">Float</div>
<div class="right">Float</div>

<p>. . .</p>

<p>. . .</p>

<p>. . .</p>

<p>. . .</p>
.left {
  float: left;
}

.right {
  float: right;
}

div {
  margin: 1em;
  width: 150px;
  height: 100px;
  border-radius: 5px;
  background-color: beige;
  padding: 1em;
}

p {
  border-radius: 5px;
  background-color: orange;
  padding: 1em;
}

Clearing float

Notice that when the <div> boxes are floating, all subsequent <p> elements will move up to fill their original space.

If you want to change this default behavior, meaning you don't want the floated boxes to affect the layout of other elements, you can clear the side effects of float using the clear property.

<h2>Lorem ipsum dolor sit</h2>

<div class="left">Float</div>
<div class="left">Float</div>
<div class="right">Float</div>

<p class="clear">. . .</p>

<p>. . .</p>

<p>. . .</p>

<p>. . .</p>
.clear {
  clear: left;
}

The clear property takes four values, none (default), left, right, and both.

When set to left, the side effects of left floated boxes will be removed.

Try this in the playground, and you'll see that the two <div> boxes are still floating next to each other, but the <p> element is no longer affected.

When set to right, the side effects of right floated boxes will be removed, and when set to both, the side effects of all floated boxes will be removed.