CSS: CSS Float & Clear
Last updated: 2026-10-13
Float was CSS's primary layout method before Flexbox and Grid. While modern layouts prefer Flexbox/Grid, understanding float is still important — you'll encounter it in legacy codebases.
Float Properties Quick Reference
| Property | Common Values | Purpose |
|---|---|---|
float |
left, right, none |
Float direction |
clear |
left, right, both, none |
Clear float effects |
1. Float Property
float makes elements "float" to one side of their container, with other content wrapping around them.
▶ Example
▶ Try it Yourself(1) Float Behavior
▶ Example
▶ Try it Yourself2. Float Problems: Height Collapse
When all children are floated, the parent "forgets" to wrap them:
▶ Example
▶ Try it YourselfResult: Parent border hugs the top, children overflow — because floated children don't occupy document flow space.
3. Clearing Floats
(1) Using clear Property (Traditional)
▶ Example
▶ Try it Yourself(2) Parent overflow
▶ Example
▶ Try it YourselfUses BFC (Block Formatting Context) behavior.
(3) Pseudo-element Clearfix (Recommended)
The standard, recommended method:
▶ Example
▶ Try it Yourself4. Modern Alternative: Flexbox
Most float layouts can now be replaced with Flexbox or Grid:
▶ Example
▶ Try it Yourself❓ FAQ
Q Is float still used for layouts?
A Not recommended. Float was designed for text wrapping, not layouts. Flexbox and Grid have perfectly replaced float layouts. Only use float for "image + text wrap" effects — that's its correct modern use case.
Q What is clearfix?
A clearfix is a classic hack for clearing float effects. Add
::after { content: ""; display: block; clear: both; } to the parent container to make it "wrap" floated children. With Flexbox or Grid, clearfix is unnecessary.Q What to do about float parent height collapse?
A Height collapse happens because floated elements leave the document flow — the parent can't detect their height. Solutions: set
overflow: hidden on parent, use clearfix, or switch to Flexbox layout.📖 Summary
- Float was once CSS's main layout method, now largely replaced by Flexbox and Grid
- The core float problem is "height collapse" — the classic fix is clearfix pseudo-element
- For new projects, use Flexbox or Grid; for text-wrap effects, float is still the best choice
📝 Exercises
- Create an image-and-text page with the image floating left and text wrapping around it.
- Use float to implement a "three-column layout" — left 200px, right 200px, center adaptive.
- Demonstrate "height collapse" and solve it with at least three methods (clearfix, overflow, pseudo-element).
- Rewrite the float three-column layout using Flexbox and compare code differences.