
Using clears on floated elements
Floats are great for positioning elements on a web page, but it has one serious drawback. When an element is floated is taken out of the page’s flow. Meaning that it is no longer considered when the pages width and height is determined by the browser. So, a wrapping element would not see it and could lose it’s height altogether.
Perhaps, a demonstration would go further in explaining this. First we want to create our container element and float an image to the left while having some text flow to the right. Here is the standard markup.
<div id="example-container">
<img src="http://media.cheekymonkeymedia.ca.s3.amazonaws.com/wp-content/uploads/2011/09/meat.jpg" alt="" title="meat" width="250" height="343" class="alignnone size-full wp-image-360" />
<p>Filet mignon chuck short loin short ribs beef ribs pork chop. Shankle strip steak meatloaf, meatball tongue chicken bacon turducken t-bone biltong.</p>
</div>
then we float the image to the left using some simple css:
#example-container img {
float:left;
margin-right: 10px;
}
this is what you will end up with
Filet mignon chuck short loin short ribs beef ribs pork chop. Shankle strip steak meatloaf, meatball tongue chicken bacon turducken t-bone biltong.
As you can tell the container (in orange) does not contain the floated element. So how do we fix it? Here are three techniques I regularly use.
technique #1 – Adding a cleared element
By adding a cleared item to the bottom of the container, it will force the container to expand to hold all the elements. This will work but is not very semantic.
<div id="example-container">
<img src="" alt="" />
<p>Filet mignon chuck short loin short ribs beef ribs pork chop. Shankle strip steak meatloaf, meatball tongue chicken bacon turducken t-bone biltong.</p>
</div>
technique #2 – Adding overflow hidden
If I know that I am never going to break the dimensions of the container, I usually fall back to the overflow:hidden technique. This will force the container to contain all floats, but if you actually need to have an element overflow the container, this may not be a great solutions. Also, this particular solution does not work in IE6 which is not that big of deal to me.
#example-container {overflow:hidden}
technique #3 – Using clearfix
By adding a class of clearfix to the container element and then declaring the following in your CSS, you can create a fairly bullet proof solution.
.clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; }
.clearfix { display: inline-block; }
This works by using the pseudo selector :after and then applying the same technique as technique #1, by making the element clear all floats and forcing the container to expand.
No related posts.





