Sep 08, 2018

How To Create a Responsive Menu with UIKit?

UIKit has become my de-facto standard for any new project. It’s simple, the default look is refreshing, and there are tons of useful components and utility classes. In most cases, it gets the job done without getting in the way. However, coming from the bootstrap world, one thing I dearly missed was the collapsible navbar.

In Bootstrap, the default navbar becomes a hamburger menu on smaller screens.

Large screen


Small Screen


In comparison, the nav links in UIKit start overflowing when the screen size gets smaller creating an empty space on one side of the page. While UIKit doesn’t have a drop-in replacement for a collapsible menu, it’s possible to achieve the same thing using the off-canvas component and some utility classes.

Responsive Menu Using Off-Canvas

Off-canvas is a sliding sidebar that can be used to provide navigation links on smaller screens. You can see some of the examples in the official docs. It looks sleek, but if you prefer bootstrap’s collapsed menu, you might need to dabble with accordion component.

Here’s how I use off-canvas for my blog:

// Offcanvas. Add it to <body>
<div id="sidenav" uk-offcanvas="flip: true" class="uk-offcanvas">
    <div class="uk-offcanvas-bar">
            <ul class="uk-nav">
                <li><a class="uk-text-large" href="">about</a></li>
                <li><a class="uk-text-large" href="">blog</a></li>

// The toggling button. Add it to the navigation
<a class="uk-navbar-toggle" uk-toggle="target: #sidenav" uk-navbar-toggle-icon></a>

Once you have the mobile navigation ready, we need to ensure that it’s only visible on smaller screens. Here, UIKit’s visibility classes come in handy.

<a class="uk-navbar-toggle uk-hidden@s" uk-toggle="target: #sidenav"  uk-navbar-toggle-icon></a>

Hurray! We have a responsive menu for mobile screens.

We can use the same utility classes to hide the desktop navigation on smaller screens.

<div class="uk-navbar-right uk-visible@s">
    <ul class="uk-navbar-nav">
        <li><a href="">about</a></li>
         <li><a href="">blog</a></li>

And this our responsive navigation: off-canvas that’s only visible on smartphone and desktop navigation which is hidden on those screens. The full solution is on Codepen.

You might have noticed the duplication of nav-links in two places, which violates the DRY principle. It might be possible to avoid this by using some Javascript and CSS, but that’ll be a little more complicated for infrequently changing nav-links. My rule of thumb: when in doubt, prioritize the KISS principle.

Follow Me!

I write about things that I find interesting. If you're modestly geeky, chances are you'll find them too.

Subscribe to this blog via RSS Feed.

Don't have an RSS reader? Use Blogtrottr to get an email notification when I publish a new post.