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
rotate the before and after psuedo-elements and fade-out the middle bar to create our
Note: I am using
Note: The CodePen is using -prefix-free, which automatically adds any necessary vendor prefixes.
classListas 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.
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…
- CSS3 Transitions, Transforms, Animation, Filters and more! by Rich Bradshaw (@richbradshaw)
- Video Screencasts - #94: Intro to Pseudo Elements by Chris Coyier (@chriscoyier)