0
0
CssHow-ToBeginner · 4 min read

How to Clear Float in CSS: Simple Methods Explained

To clear float in CSS, use the clear property on an element after floated elements to prevent wrapping. Another common method is the clearfix technique, which uses a pseudo-element to clear floats automatically.
📐

Syntax

The main way to clear floats is using the clear property. It accepts these values:

  • left: clears left floats
  • right: clears right floats
  • both: clears both left and right floats
  • none: default, no clearing

Example: clear: both; clears all floats before the element.

css
selector {
  clear: both; /* clears left and right floats */
}
💻

Example

This example shows two floated boxes and a box below that clears the floats using clear: both;. The cleared box starts below the floated boxes instead of wrapping beside them.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Clear Float Example</title>
<style>
  .box {
    width: 100px;
    height: 100px;
    background-color: lightblue;
    margin: 10px;
    float: left;
  }
  .clear {
    clear: both;
    background-color: lightcoral;
    padding: 10px;
  }
</style>
</head>
<body>
  <div class="box">Box 1</div>
  <div class="box">Box 2</div>
  <div class="clear">This box clears the floats and appears below.</div>
</body>
</html>
Output
Two blue boxes side by side floated left, and a red box below them spanning full width with text 'This box clears the floats and appears below.'
⚠️

Common Pitfalls

One common mistake is forgetting to clear floats, which causes parent containers to collapse in height because floated children are removed from normal flow. Another is using clear on the wrong element or not specifying both when needed.

Also, using empty elements just to clear floats is not recommended. Instead, use the clearfix method for better structure.

css
/* Wrong: empty element to clear floats */
.clearfix-fail {
  /* no styles */
}

/* Right: clearfix method using pseudo-element */
.clearfix::after {
  content: "";
  display: table;
  clear: both;
  }
📊

Quick Reference

Here are quick tips to clear floats effectively:

  • Use clear: both; on the element after floats.
  • Use the clearfix method on parent containers to contain floats without extra markup.
  • Alternatively, set overflow: auto; or overflow: hidden; on the parent to clear floats.
  • Avoid empty elements just for clearing.

Key Takeaways

Use clear: both; on elements to stop wrapping around floated elements.
The clearfix method is a clean way to clear floats on parent containers without extra markup.
Forgetting to clear floats can cause layout collapse and overlapping content.
Setting overflow: auto; on a parent can also clear floats but may cause clipping.
Avoid using empty elements solely to clear floats; use CSS techniques instead.