DEV Community

Cover image for Less Than 10 Lines of CSS to Create a Responsive Nav Menu
Mandeep Debnath
Mandeep Debnath

Posted on

1

Less Than 10 Lines of CSS to Create a Responsive Nav Menu

Creating navigation menus are now as easy as swiping right on Tinder :P with only less than 10 lines of CSS.

Thanks to FlexBox! FlexBox is a 1D property and that's enough for a nav menu. No more floating lefts and rights, all you need is a list of menu items inside 'ul' tag. Add your logo in that list too.

Here's the HTML:

HTML



Now comes the CSS part. You just have to set the display property of the ul to 'flex' and the necessary padding.

Here's the CSS:

CSS



Now we want to push the menu to the right and the logo to the left, right? But we can't use float. We will just use one line of CSS for the '.logo' class.

Logo

Do you see that 'margin-right: auto' property??
That is doing the whole magic. That is filling all the white-spaces to the right of the logo with the menu items. That gives us the logo on the left and the menu items on the right. Isn't that awesome?


Here's the output

Nav Menu

And that was all. That's all you need to know to create a responsive nav menu. Now to go to the next level, you can add media queries to change the menu for different devices.

Here's a simple media query for an iPad device

Alt Text

You can also check it out on my CodePen profile

Thanks for reading it to this far. I'm still working on my explanations. I know, I'm no expert. I'm just a learner.
You can share any of your feedback, I appreciate all. Thanks!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay