OnlineCBT Logo OnlineCBT
CSS Tutorial
CSS · LESSON 22

CSS Floats and Clearfix

By Ratan Updated: 15 Oct 2026

Understand legacy float layouts, wrapping text around images, and the clearfix hack.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Use floats for text wrapping

A float moves a box toward one side and allows inline content to wrap around it. Floats remain useful for an image embedded in prose. For a page's main columns, flex or grid usually expresses the layout more directly.

.story__image {
  float: left;
  width: 10rem;
  margin: 0 1rem 0.75rem 0;
}
.story { display: flow-root; }
.after-story { clear: both; }

Place the image before the paragraph in .story. Text wraps beside the image while sufficient space exists. flow-root makes the story establish a new block formatting context and contain its float. The following section can use clear if it must begin below preceding floats in the relevant context.

Why a parent can appear too short

A parent containing only floated children may not acquire the height you expect from normal-flow children. This can make its background or border appear collapsed. Establishing a suitable formatting context is often a clearer fix than setting a guessed fixed height.

The historical clearfix

.clearfix::after {
  content: "";
  display: table;
  clear: both;
}

The generated clearing element is a legacy containment technique. You will see it in older stylesheets. For new code, evaluate whether flow-root expresses the same need more clearly. Do not use overflow:hidden solely as a containment trick without considering that it may clip content.

Responsive adjustment

@media (max-width: 30rem) {
  .story__image {
    float: none;
    width: 100%;
    margin: 0 0 1rem;
  }
}

On narrow screens, a full-width image can be easier to read around than a tiny remaining text column. Give an HTML image meaningful alternative text when its content matters.

Practice

  1. Wrap a paragraph around a floated image.
  2. Remove flow-root and inspect the parent border.
  3. Add a following heading and use clear to place it below the float.
  4. Rebuild a two-column application layout with grid instead of floats and compare the intent of the CSS.

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat