MEMEPh. ideas that are worth sharing...

CSS Layout - clear and clearfix


The clear Property

When we use the float property, and we want the next element below (not on right or left), we will have to use the clear property.

The clear property specifies what should happen with the element that is next to a floating element.

The clear property can have one of the following values:

When clearing floats, you should match the clear to the float: If an element is floated to the left, then you should clear to the left. Your floated element will continue to float, but the cleared element will appear below it on the web page.

Example

This example clears the float to the left. Here, it means that the <div2> element is pushed below the left floated <div1> element: 

div1 {
  float: left;
}

div2 {
  clear: left;
}

Try it Yourself »


The clearfix Hack

If a floated element is taller than the containing element, it will "overflow" outside of its container. We can then add a clearfix hack to solve this problem:

Without Clearfix

 

With Clearfix

Example

.clearfix {
  overflow: auto;
}

Try it Yourself »

The overflow: auto clearfix works well as long as you are able to keep control of your margins and padding (else you might see scrollbars). The new, modern clearfix hack however, is safer to use, and the following code is used for most webpages:

Example

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

Try it Yourself »

You will learn more about the ::after pseudo-element in a later chapter.