Some time ago I was working on a site design that required equally-spaced, justified horizontal navigation links. The navigation bar needed to take up the full width of its container and the nav links could all be of different widths.
The left and right-most links needed to line up with the edges of their enclosing container. This sounds like something that should be easy to do in CSS but surprisingly, it isn’t! So I looked into a few ways of doing it.
Solution One – Using a jQuery Script
Coming up with a pure CSS solution that worked in older browsers was elusive. So I ended up writing a jQuery script that calculates the precise amount of white space needed between each link. it works well, is supported in older browsers and you can download it from Github. But it always bugged me that I wasn’t able to figure out a pure CSS solution. So I posted a question on StackOverflow to see what others would come up with…which brings me to solution two.
Solution Two – Using the Flex-Box model
A clever developer on StackOverflow came up with a way to lay out the nav links using the new CSS box-flex model. His solution uses
box-flex: 1 with
display: box. The solution works very well but unfortunately it doesn’t work at all in older browsers (IE 9 or below). But, if you know you’re going to be using a cutting edge version of IE or another modern browser, this solution is the Ticket! But I still wanted a CSS-based solution that would work on older browsers, so I went hunting on StackOverflow again. And then…
Solution Three – Using text-align:justify and :after Content
I found a really neat solution on StackOverflow that uses
text-align: justify and the
:after pseudo-element to correctly space the nav links apart. It works by injecting a full-width child element into the nav, which makes
text-align:justify work to space the links. But it also injects extra, unwanted vertical space below the nav links. I scratched my head about this, and decided to post yet another question on it– and I got a very interesting answer.
The problem is that the parent container needs to have
font-size:0 set in order to remove the extra vertical space. I’m not sure if Google’s search bot would perceive this as a problem or not. But, it’s a clever solution that is definitely worthy of consideration and it should work back thru IE 8. If you want a code snippet to try out, here is the Github gist.
So, there you go– three solutions for justified navigation links, each with their own advantages. Hopefully one of these techniques will work well for you. Let me know if you know of another solution that works well!