April 12, 2016
How-to: Building a horizontal nav bar without CSS floats
We’ve all dealt with issues related to floated elements in CSS layouts. Depending on which browser you’re currently supporting, the issues with floats can vary wildly. The problem that I run into most often is the need to put in a clearfix into every project.
Thanks to CSS preprocessors like SASS, it’s really easy to litter CSS files with clearfixes or any of the other auto clearing float techniques that are out there. There’s an easier way to tackle the problem of getting your elements to display inline.
Getting your elements to render inline without the need for floats solves problems. For starters, by using inline-block in your CSS instead of floats, the elements maintain their flow within the layout. This means that you can get rid of all of those instances of clearfix in either your markup or your stylesheets.
With inline-block, you can also get elements to render inline and be aligned center or right without the need to change your markup ordering.
One thing that needs to be accounted for when using inline-block is code whitespace. You can accommodate for this with a right margin of -4px.
There are other ways to solve this though.
One option is to remove all whitespace between the nav list items entirely. This works, but code readability and maintainability are compromised.
Another option is to use HTML comments to hide the whitespace — placing them between list elements to clean up any whitespace.
The HTML comment method is my preferred way of preventing inline-block from showing the extra whitespace. It can get a little tricky when building templates, but code readability is preserved.