CSS Animated Hamburger Icon

Problem

I’ve been working more on mobile web these days and thought it would be fun to animate the prolific hamburger nav icon.

Non-Animated CSS Hamburger Icon

You could use Font Awesome or an image to represent the hamburger, but those aren’t necessary. Instead, you can create a version of the hamburger only using CSS and the following markup.

The following CSS will make the span the meat of the hamburger and the before and after pseudo-elements will serve as the buns.

The above HTML and CSS are visually represented in the following CodePen. Nothing fancy here, just a hamburger icon… but this does lead us into our next section on animation.

See the Pen GxCAn by Elijah Manor (@elijahmanor) on CodePen.

Animated CSS Hamburger Icon

Now, we get to the fun stuff… let’s animate this hamburger icon! The intent we are going for is to change the hamburger into an X so the user knows to click it again to close the menu.

In CSS we are using a transition and transform to rotate the before and after psuedo-elements and fade-out the middle bar to create our X shape.

Note: I am using transition and transform, which is supported in IE10+ & other browsers. If you really wanted oldIE support, then you could use a jQuery fallback or some other JavaScript solution.

Note: The CodePen is using -prefix-free, which automatically adds any necessary vendor prefixes.

In order to kick off our animation we can toggle a class on our hamburger when the user clicks with the following JavaScript.

Note: classList as limited support (IE10+ & other browsers). You could easily use a jQuery snippet instead or provide a polyfill via HTML5 Please.

The following is an example of the above CSS Hamburger icon along with the CSS animation. You’ll need to click on the hamburger to invoke the animation.

See the Pen CSS Animated Hamburger Icon by Elijah Manor (@elijahmanor) on CodePen.

Conclusion

I hope you enjoyed this brief look into CSS peudo-elements and animation. I didn’t go into a lot of detail of exactly how everything is put together. To dig deeper with these concepts I encourage you to look into the following resources…

If you enjoyed this post, please consider sharing it with others via the following Twitter or Reddit buttons. Also, feel free to checkout my egghead.io profile page for addition free and subscription lessons, collections, and courses. As always, you can reach out to me on Twitter at @elijahmanor. Thanks and have a blessed day!

Reddit