CSS: clearing floats with positioning

How CSS floats and absolutely positioned element interact? First of all, an absolutely positioned element cannot be floated. This is simple to understand: floating and absolute positioning are virtually incompatible to each other because the former requires that other elements are aware of the presence of a float whereas the latter completely removes elements from the normal flow so that other elements are not aware of their presence. But what happens when floats are contained within an absolutely positioned element? Simply put, they're self-cleared and contained.

Suppose that we have an HTML structure like this:

<div id="container">

 <div id="wrapper">
 
  <div class="float">Float</div>
  <div class="float">Float</div>
  <div class="float">Float</div>
 
 </div>

</div>

With the following styles:

#container {
 width: 500px;
 height: 200px;
 position: relative;
 border: medium solid teal;
 position: relative;
}

#wrapper {
 width: 400px;
 position: absolute;
 top: 0;
 left: 0;
 background: silver;
 padding: 0.5em;
}

div.float {
 float: left;
 width: 100px;
 padding: 0.5em;
 margin-right: 4px;
 background: orange;
}

The elements with class float will be self-cleared and contained within their parent element, as shown below.

This technique can actually be used to clear and contain floats within a given context. However, you should always set a context for absolute positioning (in this case is the element with ID container), or you'll end up with having your container positioned against the whole viewport, as the specifications say.

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.