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.
Here is a typical nav bar that has been created using
display: inline-block rather than the typical floats that one might use.
One thing that needs to be accounted for when using
inline-block is code whitespace. In the example above, I’ve used a right margin of -4px to accommodate for the the whitespace. There are other ways to solve this though.
One option is to remove all whitespace. In this example, I’ve removed the right margin and any whitespace between the nav list items. This works, but code readability and maintainability have been compromised.
Another option is to use html comments to hide the whitespace. In this example, I’ve used HTML comments between the list elements in order 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.