CSS Float and Clear

What Is Float?

The float property allows elements to shift to the left or right within their container, enabling surrounding text or inline elements to wrap around them.

This was originally designed to wrap text around images, but it became a layout mechanism in early CSS.

img {
  float: left;
  margin-right: 20px;
}

Float Left and Right

You can float boxes to the left or right of their container. This allows you to create side-by-side columns or align content neatly.

.left-box {
  float: left;
  width: 50%;
  background-color: lightblue;
}

.right-box {
  float: right;
  width: 50%;
  background-color: lightcoral;
}
Left Column
Right Column

Float Collapse Problem

When all children inside a parent container are floated, the parent may collapse and have a height of zero. This can break layouts.

Fix it using overflow or clearfix techniques:

.container {
  overflow: hidden;
}
.clearfix::after {
  content: "";
  display: table;
  clear: both;
}

Using Clear

The clear property is used to prevent elements from wrapping around floated siblings. You can clear left, right, or both directions.

.clear-block {
  clear: both;
}

Common Float Layout

Float was a traditional layout tool for side-by-side content. Although Flexbox and Grid are now preferred, float is still useful for wrapping images or simpler layouts.

Practice Prompt

Create a float layout with:

  • Two boxes: one floated left, one floated right
  • A full-width block that clears both and appears below
<div style={{ overflow: "hidden" }}>
  <div style={{
    float: "left",
    width: "45%",
    backgroundColor: "#add8e6",
    padding: "10px",
    boxSizing: "border-box"
  }}>
    Left Float
  </div>
  <div style={{
    float: "right",
    width: "45%",
    backgroundColor: "#f08080",
    padding: "10px",
    boxSizing: "border-box"
  }}>
    Right Float
  </div>
</div>

<div style={{
  clear: "both",
  backgroundColor: "#90ee90",
  padding: "10px",
  marginTop: "10px"
}}>
  Cleared Content
</div>

You can copy and paste this code in your IDE to run!

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic