CodeBlanks Logo Icon CodeBlanks

Clear and clearfix

CSS course · Beginner · Lesson 76/82

Learn clear and clearfix techniques.

End the float flow: clear

When an element is floated left with float: left, the block elements that follow may also sit beside it. Sometimes you do not want that; a footer, for instance, should always sit below the floated image.

The CSS clear property cuts the float flow. Its values are left, right, both, and none. clear: both is the most common: it pushes the element below both left and right floats.

Clearfix: pull the container together

When a container holds only floated children, its height collapses to zero and the children spill out. This is an old headache. The fix is the clearfix technique.

A common method: give the container a .clearfix class and add content: "", display: table, and clear: both to its ::after pseudo-element. The pseudo-element drops an invisible block at the end and pulls the height back together.

Exercise Write the clearfix pseudo-element

Write a .clearfix::after selector. Add content: "", display: table, and clear: both declarations inside it. The pseudo-element drops an invisible block at the end and pulls the container's height back together.

Show example solution
/* clearfix pseudo element */
.clearfix::after {
  content: "";
  display: table;
  clear: both;
}

Test yourself

  1. What does clear: both do?

    footer {
      clear: both;
    }
    • Pushes the footer below both left and right floats
    • Floats the footer to the left
    • Hides the footer
    • Floats the footer to the right
    Show answer

    Pushes the footer below both left and right floats — Correct. clear: both pushes the element below both left and right floats.

  2. Drop the footer below floats

    footer {
      ____;
    }
    Show answer
    footer {
      clear: both;
    }
  3. Match each clear value to its meaning

    both
    Clears both sides
    left
    Clears left floats
    right
    Clears right floats
    none
    Clears nothing

All lessons in Beginner