Creating a Responsive Navbar

A usable navigation bar is an essential part of any website. By using CSS Flexbox and media queries, you can create a responsive navbar that adapts seamlessly from desktop to mobile.

On large screens, navigation links are usually displayed in a horizontal row across the top of the page. On mobile screens, however, there isn't enough horizontal space to display all the links side-by-side. If you have a small number of links, one common solution is to stack the links vertically on smaller devices.

Building the HTML Structure

First, set up your HTML using semantic tags. We'll use a nav element as the outer container, hold our "brand" or "logo" in a standard link, and place our navigation links inside an unordered list (ul) made up of list items (li):

Styling the Desktop View

To place the logo on the left and the links on the right, we apply display: flex; and justify-content: space-between; to the main container. We also use flexbox on the ul class (.nav-links) to align the links horizontally:

Styling the Mobile View

To make it responsive, we use a CSS media query. When the screen drops below a certain width (like 600px), we change the flex-direction of both the main navbar container and the list of links to column. This forces everything to stack vertically:

Full Working Example

Below is the complete HTML and CSS for a responsive navbar. Notice how some borders are added in the mobile layout to clearly separate the stacked links:

View Output Full Screen Preview

Tip: Taking it a Step Further

While stacking the links is a great start, a very long list of links can still overwhelm a small mobile screen. You can solve this by hiding the stacked links behind a clickable button. For a complete guide on this technique, see How to Create a Hamburger Menu.