CSS: floated images clearing and containing

One of the most common uses of the float property is to align images to the left or right side of a block of text, for example a paragraph. However, problems arise when the image is much bigger than the overall height of the paragraph. Remember that by default this height is given by the amount of text contained within the paragraph itself. Now suppose that we have this situation, summarized in the following CSS code:

   .alignleft {
  float: left;
  margin: 0 5px 0 0;
 .container {
  background: silver;

We've only added a silver background to the paragraph containing the floated image, and that's the result:

As you can see, the paragraph following the first one is still affected by floating and its text surrounds the lower edge of the image. If we want to fix this problem, only a few code is required:

 .clear {
  overflow: hidden;
  height: 100%;

If we apply the above rule to the container paragraph, we'll get the following result:

That's what we did want. Some developers think that applying the clear property to the floated image can also fix this problem. Let's try this approach:

 .clear-img {
  clear: left;

If we apply the above rule to the floated image, we'll get this result:

It doesn't work, because the clear property only prevents other floats from being displayed on the same line of the first one, but it does not contain the floated image itself.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.