CSS Floats Explained

CSS floats are quite well covered all over the place, but finding all the information in one place can sometimes be tricky. It took me quite a while to understand how floats work when I started out. And once I started using them that opened a whole new can of worms. In this post I am going to show you how I use floats everywhere. It seems to work quite well :) .

Lets start out with some simple HTML. You want to position two divs next to each other.

<div class="main_content">
  <h2>Hello</h2>
  <p>Welcome to my website</p>
  <img src="/tag/floats/img/me.jpg" alt="A picture of me" />
</div>

<div class="sidebar">
  <ul class="main_menu">
    <li><a href="home.html">Home</a></li>
    <li><a href="about.html">About</a></li>
    <li><a href="contact.html">Contact</a></li>
  </ul>
</div>

Ok, we have a very simple HTML snippet. We have two container divs that hold the main content and the sidebar. The main content contains a title, paragraph and an image the sidebar contains the main menu.

To float them together you would create some CSS like this:

.main_content,
.sidebar {
  float: left;
}

.main_content {
  width: 600px
}

.sidebar {
  width: 200px;
}

That isn’t very complicated either. If you ran that code you would see the two divs floated nicely next to each other. But what happens if you want to wrap our current code in another div with a background colour?

<div id="container">
  <div class="main_content">
    ...
  </div>

  <div class="sidebar">
    ...
  </div>
</div>
#container {
  width: 800px;
  padding: 20px;
  background: #333;
}
  ...

That’s cool, the only trouble is that your container is not going to wrap around the the two floated divs, so it will just be a red stripe at the top. Why does this happen? Because the divs are floating. Don’t worry there are ways to fix this. I am going to show you two:

#container {
  width: 800px;
  padding: 20px;
  background: #333;
  overflow: hidden;
}

Setting the overflow to hidden with will make the container div wrap around the floating divs. I have no idea why it does this, but it works :D . The other way is to create a CSS clear class.

.clear {
  height: 0;
  clear: both;
  overflow: hidden;
}

You can then use it like this:

<div id="container">
  <div class="main_content">
    ...
  </div>

  <div class="sidebar">
    ...
  </div>
  <div class="clear"></div>
</div>

Leaving empty divs lying around is neither pretty nor possible sometimes. If you are using a content manage like Drupal or WordPress they put together HTML for you and sometimes it is not possible to alter that.

I like using the first way, where you just set the overflow on the container to hidden, that works for probably 90% of all floating. For the other 10% create a clear class and use that.