CSS Float and Clear Property

The float property moves an element to the left or right, and the text and other inline content wrap around it. It was made for images in text, like in a newspaper.

.photo { float: left; margin: 0 12px 8px 0; width: 80px; height: 80px; background: #90caf9; }
Output in the browser

This text wraps around the floated box. The box is moved to the left, and the paragraph flows on its right side and then below it, as long as there is text. This is how images are placed in an article.

Value of floatMeaning
leftFloat to the left
rightFloat to the right
noneNo float (default)

The clear property

clear stops an element from wrapping around floats. It moves it below the floating box.

.footer { clear: both; }   /* left, right or both */

The collapsed parent problem and the clearfix

A parent does not grow for its floating children, so it can collapse to a zero height. The classic fix is a “clearfix” class.

.clearfix::after {
  content: "";
  display: table;
  clear: both;
}
<div class="clearfix">
  <div class="photo">...</div>
</div>

Another easy fix is overflow: auto (or display: flow-root) on the parent.

Note: Years ago float was also used to build page columns. Today do that with Flexbox or Grid. Use float only to wrap text around an image.

Summary

  • float moves an element left or right and text wraps around it.
  • clear stops wrapping. Use a clearfix when the parent collapses.
  • Prefer Flexbox and Grid for layouts.
  • Next: CSS Overflow.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.