I am a Web Designer and Developer
working at GitHub

My passion is building beautiful products and working with wonderful people.

Let’s chat

Clear Fixes

There is a common problem in front end engineering where, when you float an element it is actually removed from it’s parents’ flow. This can cause the elements below the floating element to run into the floating elements. Like below. The green box is floating and it’s parent has the red border. The blue box is below the red border box.

There are a few solutions to this, but I have heard of a new solution that I don’t think is widely published. overflow:hidden;

First lets go through the other solutions.

clear:both

This is the most common that I’ve found, and the one I’ve used the most. The style in this code is inline, but typically you can create a class called .clear and apply these styles.

<div style="border:1px solid red;">
  <div style="background-color:green;float:left;width:20px;height:20px;"></div>
  <div style="clear:both;"></div>
</div>

In this example you place another element at the end of the child elements in the red border box. This last element gets applied the style clear:both which disallows any floating elements on either side of it.

This can run into problems if you have multi-column layouts this can clear the content in the other columns

clearfix hack

This is essentially taking the previous method and adding to it. I don’t use this very often.

.clearfix:after {
  content: ".";
  display: block;
  clear: both;
  visibility: hidden;
  line-height: 0;
  height: 0;
}
.clearfix {
  display: inline-block;
}
html[xmlns] .clearfix {
  display: block;
}
* html .clearfix {
  height: 1%;
}

This method works but it feels like a lot of overhead, and now my CSS is non-standard.

overflow:hidden

In this method you apply overflow:hidden to the parent element which is the red border box. And that’s it!

<div style="border:1px solid red;overflow:hidden;">
  <div style="background-color:green;float:left;width:20px;height:20px;"></div>
</div>
<div style="background-color:blue;width:50px;height:50px;"></div>

Pretty simple! And it doesn’t require extra div tags. I’ve tested this in IE7, Firefox, Safari, and Chrome works in all.

ad

css

jonrohan This post was hastily written by Jon Rohan

List of Git Contributors Creating Triangles in CSS

Related Posts