Make Sure Your Columns Don’t Collapse Horizontally

Avatar of Chris Coyier
Chris Coyier on

You might be familiar with elements collapsing vertically. If an element only contains other elements that are floated, the parent element will collapse to zero height. We often employ the clear fix for that. But if an element doesn’t contain anything, it can collapse horizontally as well, which can be quite awkward for layout.

Here’s an example of some HTML for a three-column layout.

<div class="grid grid-bad">
  <div class="col col-1-3"></div>
  <div class="col col-1-3"></div>
  <div class="col col-1-3">
    I'm the last column.
  </div>
</div>

Floats are still probably the most practical way to handle columns for now. We might use a really simple grid system like this:

.col {
  float: left;
}
.col-1-3 {
  width: 33.33%
}

If you’re like me, you might have a mental model of that something like:

But you might be surprised. Because those first two columns are empty and have nothing else to give them any height, they collapse horizontally. The last column, because it does contain some content, will respect it’s width, but appear along the left, because the two columns before it have collapsed.

When This Might Happen

I came across it recently in a situation where the content of a column was loaded with Ajax. The column otherwise contained nothing, so until that Ajax call was successful and the content added, it was collapsed in width. When the content did come in, it shifted all the columns after to the right. Awkward.

See the Pen gBCfl by Chris Coyier (@chriscoyier) on CodePen

It may never come up for you. Perhaps your columns always contain some kind of content. No big deal then. But if you are making a grid framework, even for yourself, you should probably consider this scenario.

How To Fix It

The columns need some kind of something to give them at least 1px of height. With that, they won’t collapse in width. Sometimes columns have padding, that works fine. If a column has top or bottom padding, or top or bottom border, you’re set. If not for that, you can just set a min-height.

/* Any of these with positive lengths will work */

.col {
  border-top: 1px solid white;
  border-bottom: 1px solid white;
  padding-top: 1rem;
  padding-bottom: 1rem;
  min-height: 1px;
}

So yeah, not super common, but if you’re making a grid system you might as well have something in there to prevent collapsing.