Don't Float the Mainstream


Floating elements is a very common technique when writing CSS. When I first learned about layout in CSS, using floats was the go-to practice. Today, I use floats as little as possible and only when necessary. My primary technique for laying out web pages is using inline-block.   A floated element allows surrounding content to wrap around it. I believe that this is the only case that calls for using a float. When it comes to page layout, using floats can lead to many problems. One problem occurs when floating multiple elements of varying heights. This problem can be seen in the example below.  


The problem with floating elements of variable heights

One div gets "stuck" on the div with the largest height, and this completely breaks the layout. Of course you can work around this issue, but it highlights a big problem when using floats for layout.  

See the Pen Float vs. Inline-block by Zack Piper (@zpipe07) on CodePen.


The solution

Now let's approach this situation using inline-block. With just a few changes to the CSS we can achieve a much more desirable outcome. Using inline-block also allows us to use the vertical-align property which adds even more flexibility to our layout.  

See the Pen Float vs. Inline-block by Zack Piper (@zpipe07) on CodePen.

 

It has to be noted that when using inline-block elements whitespace is something that must be considered. If there is whitespace between two inline-block elements it will be evident in the browser. The way that I handle this issue is by setting the parent container to have a font-size of 0. This also forces me to explicitly set font-sizes for the children elements, which I like.   When I was writing this I happened to notice a real world example of the problem I mentioned above. GrubHub.com was dealing with a float issue!

   

Luckily all GrubHub's developers need to do is use inline-block and voila!

Share this post

The Author

Zack Piper

Front End Developer