North Dallas Developers Online Curricula

Hands-On CSS Layout

Why Some People Think Floats Are Gross

Other than just being an awkward way of talking about layout, floats have some oddities that people find annoying.

Two elements cannot float next to each other if the width of the two is greater than the available width of the container.

<div class="left">Left</div> <div class="right">Right</div>

div, span {
  float: left;
  min-height: 200px;
  width: 51%;
}

.left {
  background-color: #DDD;
}

.right {
  background-color: #AAA;
}

This often annoys people but at the same time it enables some interesting things.

Width is determined by the following formula unless you change the box sizing: left margin + left border + left padding + content width + right padding + right border + right margin.

That’s only true if you don’t change the box model, but perhaps more on that later.

I recommend always setting an explicit width for floated elements so they will behave consistently.

This is especially good to keep in mind when the content can change over time.

Clear your floats when you are done with them so that the float behavior gets turned off.

<div class="left">Left</div> <div class="right">Right</div> <p>This is a paragraph and I don’t have it floated!</p>

div, span {
  float: left;
  min-height: 200px;
}

.left {
  background-color: #DDD;
}

.right {
  background-color: #AAA;
}

p {
  clear: both;
}

Floats take the floated elements out of the normal document flow, and this can have some strange side-effects. So “clear: both;” on the following element or use some sort of clearfix strategy.

If all the child elements of a container are floated, that container will collapse its size unless an overflow value is set.

<div class="outer"> <div class="inner">First</div> <div class="inner">Second</div> </div>

.outer {
  background-color: #AAA;
  overflow: auto;
}

.inner {
  background-color: #DDD;
  float: left;
  margin: 5px;
}

Remove the overlow then the float and see what happens.

When using floats for columns, there is no great way to keep all the columns the same height.

The height of a float is by default determined by its content size and two different floated elements do not keep their height in sync. Hacks include specifying height or min-height (which limits flexibility), using a background image with two different background colors in a containing div to visually fake columns.

Exercise

Remember the horizontal menu we made with inline-block? Use floats instead.