🌱BeginnerCSS Layout Basics
CSS Float and Clear
Learn how floats work for wrapping text around images and how clear prevents unintended wrapping.
Overview
`float` was originally designed to allow text to wrap around images like newspaper columns. An element with `float: left` or `float: right` moves to the left or right edge of its container, and surrounding content wraps around it.
Floated elements are partially removed from the normal flow: inline content wraps around them, but block-level siblings may ignore them (causing the "collapsed parent" problem).
The `clear` property stops an element from wrapping next to a float. `clear: left` moves an element below any left floats; `clear: both` moves below all floats.
**Today's context:** Floats are mostly used for text-wraps around images. For page layouts, use Flexbox or Grid. Understanding floats is still important because many legacy codebases and CSS frameworks use them.
Key Points
- •float: left/right moves element to the side; text flows around it
- •Floated elements are removed from normal block flow
- •clear: left/right/both prevents next element from wrapping alongside floats
- •Parent element collapses if all its children are floated fix with clearfix
- •overflow: hidden on parent also clears floats (but clips overflow)
- •Use flexbox/grid for layouts; floats are primarily for text wrapping images
Examples
Float image with text wrap
img.thumbnail {
float: left;
margin: 0 16px 8px 0; /* space between image and text */
width: 200px;
}
/* Text in the same container wraps around the image */This is the classic and still valid use case for float.
clear to stop wrapping
.author-bio {
float: left;
width: 30%;
}
/* Footer should NOT wrap next to the float */
footer {
clear: both; /* moves below ALL floats */
}Clearfix fixing collapsed parent
/* The modern clearfix */
.clearfix::after {
content: '';
display: block;
clear: both;
}
/* Apply to any parent whose children are floated */
/* <div class="clearfix">
<div style="float:left">...</div>
</div> */The clearfix hack inserts an invisible element after the floated children to force the parent to contain them.
Common Mistakes
- Forgetting to clear floats causes parent collapse and layout breakage
- Using floats for complex page layouts use flexbox or grid instead
- Not adding margin to floated images text butts right up against them
Note
If you are starting a new project, use Flexbox or Grid for layout and only use float for text-wrapping images. Legacy code often uses float-based grids recognizing clearfix patterns helps you read and maintain it.
Exercises
Write CSS to style the HTML scaffold. The preview updates live — when it looks right, mark as done.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4