Tailwind Tidbit - Vertically Align Icons and Text in Buttons

Published May 1st, 2020
3 minute read

While building buttons with Tailwind CSS, you might notice icons and text don't vertically align just right. Sometimes they do, but if you look close they're probably off by a tiny bit. Sure it's only a pixel or two, but design is often in the details. Those pixels could be the difference between your button looking just okay, and really professional.

Say we have a button with an SVG icon in it like this:

(see how the icon isn't aligned perfectly?)
<button class="px-3 py-2 font-medium rounded px-4 py-2 leading-5 bg-green-500 text-primary-100 text-white hover:text-white hover:bg-green-700">
    <svg class="inline-block w-5 h-5" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" stroke="currentColor" viewBox="0 0 24 24"><path d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"></path></svg> Woohoo!
</button>

Luckily the solution is simple. Instead of any margin or padding hacks, we can just use flexbox! Apply the inline-flex items-center utility classes to the anchor tag.

(Ahh, muuuch better)
<button class="inline-flex items-center px-3 py-2 font-medium rounded px-4 py-2 leading-5 bg-green-500 text-primary-100 text-white hover:text-white hover:bg-green-700">
    <svg class="inline-block w-5 h-5 mr-1" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" stroke="currentColor" viewBox="0 0 24 24"><path d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"></path></svg> Woohoo!
</button>

You'll probably also need to add some margin to the inner SVG element. In this example I added mr-1 to space out the icon horizontally. This is because having inline-flex on the containing element causes the svg and text to become flex children (instead of regular inline elements) which butts them right up against one another.

Hope you found this helpful! What are your favorite little tricks with Tailwind? Let me know on Twitter and I'll be sure to give you credit in the next tidbit!

Enjoy this article? Follow me on Twitter for more tips, articles and links.
😢 Awww, nobody has liked or mentioned this on Twitter yet.

Join the Newsletter ❤️

A most excellent monthly newsletter with code & design tips, curated links and more!
Don't worry, I'll never send you spam. Unsubscribe at any time.