CSS Components #1 "Hamburger Menu"

Posted 17th Nov 2018

The hamburger menu has been widely used as an icon typically placed in the top corner of a website interface, its use is to toggle a hidden menu (usually for mobile websites or apps).

One of my biggest fascinations with CSS is that almost anything can be created using it, without the use of external images.

I wanted to create a mini series that shows how easily this can be done, and showcase the code used so you can use it yourself within your own website.

Another reason I love working with CSS is that there are many ways to create the same end result.

I created a few rules for myself before heading into this;

1. The whole area of the icon must be clickable. No using negative margins to throw elements outside of the parent overflow.

2. Use as little HTML elements as possible.

3. Must but accessible to screenreaders.

My first attempt uses pseudo elements (:before & :after). They are stacked, then use white borders to separate each element and a bottom margin on the top line to reveal the black underneath, creating the middle line. Have a look at the code yourself.

The only dislike I have about this method is that this icon won’t work on a background that isn’t solid, as it relies on setting the solid background colour to create the ‘gaps’ between the lines.

To fix that, I had to use another element. I chose to use an ‘i’ tag, simply to keep the code as small as possible.

The great thing about this method is I have control over each of the lines. This means we have the ability to customise our menu icon a lot more. Hover over the icon to see a small animation - this wouldn’t have been possible the first method.

I’m sure there are many other ways to create the same icon, these are just a couple I came up with while writing this post.

Stay tuned for the next component in this series.