Floats and clearing floats

In CSS, the `float` property is used to move an element to the left or right of its container, allowing other elements to wrap around it. However, floating an element can cause its container to collapse, which is where clearing floats comes into play.

Floating Elements

When an element is floated, it is removed from the normal flow of the document and placed to the left or right of its container. This can be useful for creating layouts where content needs to flow around an image or other element.

Here is an example of how to float an image to the left of its container:

img {
  float: left;

Clearing Floats

When an element is floated, its container will no longer take up the space occupied by the floated element. This can cause layout issues, such as a container collapsing or content overlapping. To fix this, you can use the `clear` property to force a container to start on a new line after any floated elements.

Here is an example of how to clear floats after an element:

.clearfix {
  clear: both;

The `clearfix` class can then be added to the container after any floated elements to ensure that it takes up the full height of its content.

Using Floats for Layout

Floats can be used to create complex layouts in CSS, such as multi-column designs or text wrapping around images. However, it's important to use them carefully, as they can also cause unexpected behavior if not implemented correctly.

Here is an example of a multi-column layout created using floats:


<div class="wrapper">
  <div class="column">Column 1</div>
  <div class="column">Column 2</div>
  <div class="column">Column 3</div>


.column {
  float: left;
  width: 33.33%;
  padding: 20px;
  box-sizing: border-box;

.wrapper {
  overflow: hidden;

In this example, each column is floated to the left and given a width of 33.33%, which allows them to sit side-by-side within the wrapper element. The wrapper element has `overflow: hidden` applied to it to ensure that it expands to fit its content.

I hope this explanation helps you understand the concepts of floats and clearing floats in CSS!

Was this page helpful?