Mar 29, 2013

Responsive Menu Solution using FitText jQuery Plugin

I've always found one of the biggest challenges of making a responsive site look great is keeping the main navigation looking good at all screen widths.

As the width of the site gets smaller the space for each word in the menu decreases, so I would find myself adding multiple media queries to shrink the font size. For some menus this isn't a problem as there is enough space in between each item to account for it and the number of breakpoints needed is low and manageable. But in many cases it is handy to use a jQuery plugin called FitText. FitText was designed to use on headline text to force the heading to always fill up it's container.

Here is some example code for a menu using this logic:

HTML:


<nav>
    <ul>
        <li><a href="”#”">Home</a></li>
        <li><a href="”#”">The Next Page</a></li>
        <li><a href="”#”">Another Page</a></li>
        <li><a href="”#”">Last Page</a></li>
    </ul>
</nav>

JS:


<script type="text/javascript">
    $(document).ready(function(){
        $(".main-nav ul li a").fitText();
    });
</script>
CSS:

nav ul {
    list-style-type: none;
    padding: 0;
    margin: 0;
}

nav ul li a {
    display: inline-block;
    width: 25%;
    float: left;
    text-align: center;
    text-decoration: none;
}

With this code you will get a horizontal menu with your list items all equally sized and the text aligned to the center center of its 'a' tag. When you resize the browser window the font size will adjust to keep the font filling up the correct percentage of it's container.

A few things to keep in mind with this trick is that the width you set for each 'a' is based on how many items you have. It needs to add up to 100% to fill up the ul and the div. For example if you had 6 items in the menu each would be 16.66666% wide. Also the container holding the text you are calling fitText on must have display set to block or inline-block.

This technique is one of many solutions to this issue, though I find it most helpful for crowded menus that need to fill up all of the space between the left hand logo and the right side of the site.