CSS Layout - clear and clearfix

clear property

clear The property specifies which elements can float next to the cleared element and on which side.

clear The property can be set to one of the following values:

  • none - Float elements are allowed on both sides. Default value
  • left - No floated elements are allowed on the left
  • right - No floated elements are allowed on the right
  • both - No floated elements are allowed on either the left or the right
  • inherit - The element inherits its parent's clear value

used clear The most common usage of the property is when it is used on an element with float after the property.

When clearing floats, it should match the clearing with the floating: if an element floats to the left, then the left should be cleared. Your floated elements will continue to float, but the cleared elements will display below them.

The following example clears the float to the left. This indicates that no floated elements are allowed on the left side of the (div):

Example

div {
  clear: left;
}

Try It Yourself

clearfix Hack

If an element is taller than the element that contains it and it is floated, it will 'overflow' outside of its container:

Then we can add overflow: auto; to the containing element to solve this problem:

Example

.clearfix {
  overflow: auto;
}

Try It Yourself

As long as you can control the margin and padding (otherwise you might see scrollbars), overflow: auto clearfix will work well. However, the new modern clearfix hack technology is safer to use, and the following code is applied to most websites:

Example

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

Try It Yourself

You will learn this in the later chapters ::after Pseudo-elements.