CSS Float

CSS float – Complete Beginner Guide
(Concept • Syntax • clear • Examples • Common Mistakes)
What is CSS float?
The float property is used to position an element to the left or right of its container, allowing text and inline elements to wrap around it.
Originally, float was designed for text wrapping around images, not full layouts.
Syntax
Values
| Value | Meaning |
|---|---|
left | Element floats to the left |
right | Element floats to the right |
none | Default (no float) |
inherit | Inherits from parent |
Basic Example: Image with Text Wrap
Result:
Image goes left → text flows around it.
Float for Layout (Old-Style)
Works, but not recommended for modern layouts.
The BIG Problem with float
Parent Collapse Issue
When all child elements are floated, the parent height becomes zero.
Parent does not expand automatically.
Solution: clear
The clear property tells elements not to sit next to floated elements.
Example
Best Fix: Clearfix Hack
✔ Parent height restored
✔ Classic interview favorite
Common Mistakes
❌ Using float for full page layout
❌ Forgetting clear
❌ Expecting vertical centering
❌ Mixing float with Flexbox unnecessarily
Modern Alternatives (IMPORTANT)
| Layout Need | Use This |
|---|---|
| Row / column layout | flexbox |
| Complex grid | CSS Grid |
| Text wrapping | float |
Rule
Use float ONLY for text wrapping
Interview One-Liners
Float removes element from normal document flow
Parent collapse occurs due to floated children
clearfixes float overlapFloat is legacy layout method
Final Summary
✔ float positions elements left/right
✔ Text wraps around floated elements
✔ Causes parent collapse
✔ Fixed using clear or clearfix
✔ Replaced by Flexbox/Grid for layouts
