Tackling The Mobile Navbar Hamburger Positioning Issue

What we are hoping for

Let’s say you need to make a mobile navbar with CSS. It’s a simple navbar, all it needs to include is a title and a hamburger icon on the other side (like the one above).

If the icon is part of an icon font pack like Font Awesome, then your’e good to go — all you need to do is float it to the right and things look great.

The problem starts when you are given a specific icon to use, and it’s given as a .png image. In that case, it stops looking good and the text is not vertically aligned with icon:

The text is not in the same line as the icon

So you might think a simple vertical-align will fix the problem, but floated elements lose their ability to be vertically aligned.

I keep getting in to this problem and I haven’t found a nice, clean solution yet. However, I have found a couple of ways to get around it.

1. Make the navbar two equal columns and vertical align those

There are a couple of ways to do this, each with it’s own flaws.

First, we can set the width of both elements to 50% and get rid of the automatic margin between them (without float). For example:

HTML:

<nav class=”navbar”>
<h1 class=”nav-title”>Logo</h1><!-—
--><a href=”#” class=”hamburger”>
<img src=”http://www.hollandamericablog.com/wp-content/themes/twentythirteen-child/images/icon-hamburger.png" alt=””>
</a>
</nav>

CSS:

.nav-title {
margin: 0;
vertical-align: super;
}
.hamburger {
text-align: right;
}
.nav-title,
.hamburger {
width: 50%;
display: inline-block;
}

The trick is to use an HTML comment to eliminate the whitespace between the elements.

You can also use flexbox but it’s a little overkill, and it’s not yet supported in all browsers.

2. Use precise positioning to get it right

This is pretty dirty. You should use it when your navbar doesn’t really change and stays the same height with the same text sizes inside it. In that case, you can just hard-code the correct position in:

.nav-title {
margin: 0;
position: relative;
top: 6px;
}
.hamburger {
float: right;
}
.nav-title,
.hamburger {
display: inline-block;
}

I find the second option to be much quicker and more robust (in cases your title takes up more than 50%, for example).On the other hand, it’s not as responsive and you might need to add a lot of media queries.


That’s pretty much it. I am sure that there is a better, cleaner solution out there, but I haven’t found it yet. This is what I currently do and I would love to hear any other solutions.