divs working side by side


divs working side by side

When design is getting increasingly more complex, yet minimalistic these days, having shapes side by side is almost a must, yet at the same time quite a frustrating exercise with CSS. This would have been more simple in the days of tables!

It’s simple enough to place two divs side by side inside a wrapper, or container, however you may find the text inside one will word-wrap underneath another if one div is bigger (or smaller) than the other. This may escape the container altogether.

The following simple few lines of code works well, particularly if the size of the container is to be 100% of the body, and the width of one div is specified through the use of an image.

#container {
  overflow:hidden;
}
#left {
  float:left;
}
#right {
  overflow:hidden;
}

In case of setting several of these shapes on top of each other, I clear:both the container itself to be on the safe side, but it’s not really necessary as overflow is supposed to clear floats vertical and horizonal. You can float only one inside div, or you can float both to the left — as long as you don’t float one left and one right, though you would think it makes sense to!

Doing the latter makes the content appear underneath the container instead, unless this is the effect you want to achieve. The divs will no longer be side by side, but I admit it’s a nice effect all the same.

You could also use overflow:auto on the container, so that it adapts to the size of its contents without needing clear:both, but this has the potential to generate a scrollbar, apparently.