Build a Responsive Navigation Bar Using CSS Flexbox
Quick Answer: Build a flexbox navigation bar in a fixed order. Write a semantic <nav> with a logo and a list of links. Make the nav a flex container with justify-content: space-between and align-items: center. Make the list of links a second flex container and use gap for the spacing. On small screens, stack the links in a column behind a toggle button. From a breakpoint that fits the content, switch the links to a row with a mobile-first min-width media query. Use a real <button> for the toggle and keep its aria-expanded value up to date.
S1. Why Do We Need Flexbox for a Navigation Bar?
Imagine your website menu has three links and looks perfect. Then a teammate adds a fourth link, and the whole menu drops under the logo.
Every website needs a navigation bar. It is usually the first thing visitors use, and it has to work on a phone, a tablet and a wide desktop screen. The logo sits on one side, the links sit on the other side, and everything must stay centered on one line.
Would you set a fixed width for every part and hope the screen is wide enough? That works on one device and fails on the next one.
Flexbox solves this. It places items in a row, shares the free space between them, and lets us change the direction when the screen gets small. Let's first see what the old approach looks like.
S2. The Problem: A Navbar Built With Floats and Fixed Widths
Float-based navbar = a navigation bar whose parts are placed side by side with float and fixed widths.
Imagine a navigation bar with a logo on the left and three links on the right. The logo is 100px wide, each link is 120px wide, and the whole menu is 360px wide. The bar is shown on a narrow screen that is 400px wide.
Example 1: A float-based navbar on a narrow screen
Assumption: In the output diagrams, one character is about 20px wide and one text row is about 40px tall. L is the logo, and H, B and C are the links Home, Blog and Contact.
<!-- HTML -->
<nav class="nav">
<a class="logo" href="#">Logo</a>
<ul class="menu">
<li><a href="#">Home</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
/* CSS */
.nav { width: 400px; }
.logo {
float: left;
width: 100px;
height: 40px;
}
.menu {
float: right;
width: 360px;
margin: 0;
padding: 0;
list-style: none;
}
.menu li {
float: left;
width: 120px;
height: 40px;
}
Expected output
|LLLLL | | HHHHHHBBBBBBCCCCCC| The logo (100px) and the menu (360px) need 460px, but the nav is only 400px wide. The menu does not fit beside the logo, so it drops to a second row on the right. The nav has no height of its own, because floated children do not give it one. In a 600px wide nav the same CSS fits in one row, so the bug shows only on narrow screens.
The page renders without any error. The CSS is valid, but the layout only works at one width.
What goes wrong?
- Fixed widths: The widths add up to 460px, so there is no room on a narrow screen. A fourth link breaks the bar again.
- No height: A container with only floated children collapses, so its background or border does not appear unless a clearing trick is added.
- No vertical centering: Floats do not center items. Developers guess with
line-height, padding or margins. - Patch after patch: Each screen size needs another media query to fix the last one.
- Fragile changes: A longer label or a new link means editing several widths by hand.
Now think about a real site with six links, a search box and a translated menu with long words. Every change becomes a new calculation.
Remember: The old approach is not wrong because floats are broken. It is fragile because we decide every width in advance, and the screen decides nothing. A navigation bar should adapt to the space it gets.
Animation 1: How fixed widths break a navbar
Fixed widths meet a narrow screen
The red highlights show where the layout stops fitting.
The animation highlights the three causes that make the bar break.
S3. The Solution: One Flex Container for the Bar, One for the Links
Flexbox gives us a simpler design, and it lets the browser share the space instead of us counting pixels.
flex container = an element with display: flex. Its direct children become flex items, and they sit in a row by default.
A navigation bar needs only two flex containers.
- The
navholds the logo and the menu. It spreads them to opposite ends and centers them vertically. - The
ulholds the links. It puts them in a row and adds an equal gap between them. - A media query changes the direction of the links from a column to a row when the screen is wide enough.
Now the same bar works at any width, because the free space is shared by the browser.
Example 2: The navbar with flexbox
Assumption: Each logo or link label is about 60px wide. With 20px of padding on each side, every item is about 100px wide and 40px tall. The nav is 600px wide in this example.
<!-- HTML -->
<nav class="nav">
<a class="logo" href="#">Logo</a>
<ul class="menu">
<li><a href="#">Home</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
/* CSS */
.nav {
display: flex;
justify-content: space-between;
align-items: center;
width: 600px;
}
.menu {
display: flex;
gap: 20px;
margin: 0;
padding: 0;
list-style: none;
}
.logo, .menu a {
display: block;
padding: 10px 20px;
}
Expected output
|LLLLL HHHHH BBBBB CCCCC| The menu width = 3 x 100 + 2 x 20 = 340px. Free space = 600 - (100 + 340) = 160px. space-between puts all 160px (8 characters) between the logo and the menu. The menu is also a flex container: gap adds 20px (1 character) between the links. align-items: center keeps the items centered when their heights differ.
Notice the difference. We never wrote a width for the menu, and the bar still sits correctly. A fourth link would simply make the menu wider and the free space smaller.
Animation 2: How the flex navbar is built
Container, space, adapt
Each step uses one flexbox idea.
The animation highlights the three steps and the flexbox feature each one uses.
Compare both approaches
| Floats and fixed widths | Flexbox navbar |
|---|---|
| Every width is decided by hand. | The browser shares the free space. |
| A new link can break the bar. | A new link just uses some of the free space. |
| The container can collapse to no height. | The container keeps the height of its tallest item. |
| Vertical centering needs guesses. | align-items: center does it. |
| Direction changes need many patches. | One flex-direction change switches row and column. |
The idea to remember
- Two flex containers = the
navarranges the big groups, and theularranges the links. - Free space is the key =
justify-contentand auto margins decide where the leftover space goes. - Mobile first = write the small-screen layout first, then add a
min-widthmedia query for wider screens. - Breakpoint from content = switch to a row when the links really fit, not when a popular device width says so.
- Use a button for the toggle = it works with the keyboard, and
aria-expandedtells assistive technology if the menu is open.
S4. Step-by-Step Code Breakdown
1. Learn the properties and the widths
A navigation bar uses only a small set of flexbox properties. The table shows each property, the element it belongs to, and what it does in a navbar.
| Property | Set on | What it does in a navbar |
|---|---|---|
display: flex |
The nav and the ul |
Turns the direct children into flex items in a row |
justify-content: space-between |
The nav |
Puts the logo and the menu at opposite ends |
align-items: center |
The nav |
Centers the items vertically |
gap |
The ul |
Adds equal space between the links, and none at the edges |
margin-left: auto |
A flex item | Takes all the free space on its left side and pushes the item to the right |
flex-direction |
The ul |
Column on small screens, row on wide screens |
flex-wrap and flex-basis: 100% |
The nav and the ul |
Moves the opened menu to its own line below the logo and the button |
The same navbar behaves in two modes, depending on the width of the screen.
| Screen | Toggle button | Links |
|---|---|---|
| Below the breakpoint | Visible | Hidden until the button is pressed, then shown in a column |
| At or above the breakpoint | Hidden | Always visible, in one row with a gap |
2. Build the bar
Example 2 already showed this step. The nav is a flex container that spreads the logo and the menu to opposite ends. The ul is a second flex container that lays out the links with a gap. Remember to remove the default list style, margin and padding of the ul, or the browser adds its own space and markers.
3. Push groups apart with an auto margin
Sometimes the bar has three groups: a logo, the links and a button such as Sign in. space-between would put equal gaps on both sides of the middle group, so the links would float in the center. An auto margin gives all the free space to one side instead.
Example 3: Logo on the left, links and a button on the right
Assumption: The nav is 800px wide, and the Sign in button (S) is about 100px wide and 40px tall, like the other items.
/* CSS (HTML: a logo, the menu, then a link with class "btn") */
.nav {
display: flex;
align-items: center;
gap: 20px;
width: 800px;
}
.menu {
display: flex;
gap: 20px;
margin: 0 0 0 auto;
padding: 0;
list-style: none;
}
.logo, .menu a, .btn {
display: block;
padding: 10px 20px;
}
Expected output
|LLLLL HHHHH BBBBB CCCCC SSSSS| Used space = logo 100 + menu 340 + button 100 + 2 gaps of 20 = 580px. Free space = 800 - 580 = 220px (11 characters). margin-left: auto on the menu takes all 220px, so the links and the button move to the right end. The logo stays at the left end, and the gap of 20px stays between the groups.
4. Collapse the menu on small screens (mobile first)
Now we add a toggle button and write the small-screen layout first. The links are hidden and stacked in a column. The wide-screen layout is added later inside a min-width media query.
Example 4: Mobile-first navbar with a toggle button
Assumption: The toggle button (M) is about 80px wide. The small viewport is 360px wide, and the large one is 600px wide.
<!-- HTML -->
<nav class="nav" aria-label="Main">
<a class="logo" href="#">Logo</a>
<button class="nav-toggle" type="button" aria-expanded="false" aria-controls="menu">Menu</button>
<ul class="menu" id="menu">
<li><a href="#">Home</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
/* CSS: small screens first */
.nav {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
}
.menu {
display: none;
flex-basis: 100%;
flex-direction: column;
margin: 0;
padding: 0;
list-style: none;
}
.menu.is-open { display: flex; }
.logo, .menu a, .nav-toggle {
display: block;
padding: 10px 20px;
}
/* CSS: wider screens, written after the base rules */
@media (min-width: 600px) {
.nav-toggle { display: none; }
.menu {
display: flex;
flex-basis: auto;
flex-direction: row;
gap: 20px;
}
}
Expected output
Viewport 360px wide (18 characters), menu closed: |LLLLL MMMM| Viewport 360px wide, after the toggle adds the class is-open: |LLLLL MMMM| |HHHHHHHHHHHHHHHHHH| |BBBBBBBBBBBBBBBBBB| |CCCCCCCCCCCCCCCCCC| Viewport 600px wide (30 characters), toggle hidden: |LLLLL HHHHH BBBBB CCCCC| flex-basis: 100% makes the opened menu fill a whole line, so flex-wrap moves it below. In the column, each link stretches to the full width, so the whole row is clickable. .menu.is-open has higher specificity than .menu, so it wins over display: none. At 600px the media query rules come later and show the menu as a row again.
5. Toggle the menu with a button
The CSS is ready, but nothing adds the class is-open yet. A few lines of JavaScript switch the class and keep aria-expanded in sync, so assistive technology knows whether the menu is open.
Example 5: A small, accessible toggle
Assumption: The script runs after the nav markup, for example at the end of the body.
/* JavaScript */
const toggle = document.querySelector('.nav-toggle');
const menu = document.querySelector('#menu');
toggle.addEventListener('click', function () {
const isOpen = menu.classList.toggle('is-open');
toggle.setAttribute('aria-expanded', String(isOpen));
});
Expected output
Start: no is-open class, aria-expanded="false", the links are hidden.
Click 1: classList.toggle adds is-open and returns true.
aria-expanded becomes "true", and the links appear in a column.
Click 2: is-open is removed and toggle returns false.
aria-expanded becomes "false", and the links hide again.
At 600px and wider, the media query shows the menu as a row, and the button is hidden.
6. Choose the breakpoint from the content
A breakpoint is not a magic number. It is the width where the row of links really fits. If the menu has five links, the row needs more room than a menu with three.
Example 6: Five links need a later breakpoint
Assumption: There are now five links, each about 100px wide: H (Home), B (Blog), A (About), P (Pricing) and C (Contact). The HTML is Example 4 with two more list items.
/* CSS: only the media query changes */
/* Needed width = logo 100 + 5 links 500 + 4 gaps 80 = 680px */
@media (min-width: 720px) {
.nav-toggle { display: none; }
.menu {
display: flex;
flex-basis: auto;
flex-direction: row;
gap: 20px;
}
}
/* Visible keyboard focus */
.menu a:focus-visible {
outline: 2px solid;
outline-offset: 2px;
}
Expected output
Viewport 640px wide (32 characters), menu closed: |LLLLL MMMM| Viewport 720px wide (36 characters): |LLLLL HHHHH BBBBB AAAAA PPPPP CCCCC| At 640px a row would need 680px, which is too tight, so the stacked layout is still used. At 720px the free space is 720 - 680 = 40px (2 characters) between the logo and the menu. Keyboard users now see an outline on the link they have reached with the Tab key.
S5. Architecture and Real-World Trade-Offs
On a real project, the navigation bar is one component that is reused on every page. A team that writes it mobile first, tests it at several widths and uses a real button for the toggle gets a bar that is easy to change later.
How the design fits a project
Imagine a team working on a website with many pages. The same navbar has to behave well on every kind of screen.
One navbar, three situations
The same markup adapts to the screen and to the person using it.
The animation traces each situation to the part of the design that handles it.
Benefits for larger websites
- Adaptability: The bar uses the space it gets, so new links and longer labels need little or no extra CSS.
- Maintainability: Two flex containers and one media query are easy to read for the next developer.
- Less code: There are no clearing tricks, no per-width patches and no guessed margins.
- Accessibility: A real nav landmark, real links and a real button work with keyboards and screen readers.
- Reuse: One component serves every page of the site.
Important trade-offs
- The toggle in this article needs a small piece of JavaScript. CSS-only versions exist, but they have their own limits, so check keyboard and screen reader behavior before using one.
- The breakpoint depends on the content. When you add a link or translate the labels, test the bar again, because the width it needs may change.
- A closed menu uses
display: none, so its links are removed from the tab order. That is correct, and hiding links in other ways can leave them focusable while they are out of sight. - Dropdown submenus, sticky headers and mega menus add many more rules and accessibility work. They are outside the scope of this article.
- Flexbox arranges one direction at a time. For a header with several rows, search boxes and many areas, nesting flex containers or using Grid can be simpler.
- Browsers can differ in default styles for buttons and lists, so reset what you need and test in more than one browser.
Important: Flexbox does not make a navbar responsive on its own. It shares the space and changes the direction. You still decide where the layout changes and how the menu opens.
S6. Common Mistakes and Best Practices
Mistake 1: Putting display: flex on the wrong element
Wrong: Write .menu li { display: flex; } and expect the links to line up in a row.
Why it fails: display: flex affects the direct children of the element. Here each li becomes a container for its own link, while the ul stays a normal block, so the items still stack.
Better: Write .menu { display: flex; } on the ul, because the li elements are the items you want in a row.
Rule: Put display: flex on the parent of the items.
Mistake 2: Pushing items apart with fixed widths and margins
Wrong: Give the menu margin-left: 400px to move it to the right.
Why it fails: The number only works at one width. On a narrower screen the menu overflows or wraps, and on a wider screen it is no longer at the end.
Better: Use justify-content: space-between for two groups, or margin-left: auto on the menu for three.
Rule: Let the free space decide, not a fixed number.
Mistake 3: Hiding the menu and forgetting to show it on wide screens
Wrong: Write .menu { display: none; } and show it only with the class is-open, with no media query.
Why it fails: On a desktop the toggle button is not needed, but the menu is still hidden until someone presses a button that may also be hidden. Visitors see no links at all.
Better: Add a min-width media query, after the base rules, that sets display: flex on the menu and hides the toggle.
Rule: Every rule that hides the menu needs a rule that shows it on wide screens.
Mistake 4: Using a div as the toggle and ignoring aria-expanded
Wrong: Make the toggle a <div> with a click handler, and never update its state.
Why it fails: A div cannot be reached with the Tab key and does not respond to Enter or Space. Screen reader users are not told whether the menu is open.
Better: Use <button type="button">, and update aria-expanded each time the menu opens or closes.
Rule: Interactive controls should be real controls.
Mistake 5: Picking the breakpoint from a device instead of the content
Wrong: Copy a popular tablet width as the breakpoint, whatever the menu contains.
Why it fails: A menu with six links may not fit at that width, and a menu with two links may switch to the toggle much too early.
Better: Add up the logo, the links and the gaps, then choose a breakpoint a little above that total, as in Example 6.
Rule: The content sets the breakpoint.
S7. How This Comes Up in Interviews
Question 1: How do you build a navbar with the logo on the left and the links on the right?
What the interviewer wants: They want to see that you know which element gets which property.
Strong answer:
"I make the nav a flex container with justify-content: space-between and align-items: center, so the logo and the menu sit at opposite ends and are vertically centered. The list of links is a second flex container, with a gap for the spacing and the default list style removed."
Question 2: When would you use margin-left: auto instead of space-between?
Strong answer:
"space-between spreads the free space evenly between all items, so with three groups the middle one ends up in the center. An auto margin gives all the free space to one side, so I can keep a logo on the left and push the links and a button to the right together."
Question 3: How do you make the navbar responsive?
Strong answer:
"I write the small-screen layout first. The menu is hidden behind a toggle button and stacks in a column when opened, using flex-basis: 100% and flex-wrap so it takes its own line. Then a min-width media query shows the links in a row and hides the button. I choose the breakpoint from the width the content needs."
Question 4: How do you make the mobile menu accessible?
Strong answer:
"I use a nav element with a label, a real button for the toggle, and aria-controls pointing at the menu. The script updates aria-expanded on every click. Closed links are hidden with display: none so they leave the tab order, and I add a visible focus style for keyboard users."
What should different experience levels explain?
- Junior developer: Explain how to place a logo and links in one row with
display: flex, and howgapandalign-itemshelp. - Senior developer: Explain the mobile-first approach, how free space is shared, why a breakpoint should follow the content, and how a toggle button manages
aria-expanded. - Technical architect: Explain how a shared navigation component, tested at several widths and with a keyboard, keeps a large site consistent, and when to choose Grid or a different pattern for a complex header.
S8. Hands-On Practice
Beginner: Build the basic bar
Create the HTML and CSS from Example 2. Then change justify-content to center and flex-start, and change the gap to 40px. Look at what moves each time.
Expected result: With space-between the logo is at the left end and the links are at the right end. With center both groups sit together in the middle, and a larger gap spreads the links apart.
Intermediate: Add a button and compare two techniques
Add a Sign in link after the menu, as in Example 3. First use justify-content: space-between on the nav, and then use margin-left: auto on the menu instead.
Hint: Work out the free space and see which side of each group receives it.
Expected result: With space-between the links sit in the middle of the bar, with equal gaps on both sides. With margin-left: auto the links and the button sit together at the right end.
Advanced: Build the full responsive navbar
Build the navbar from Example 4 with five links and the script from Example 5. Calculate the breakpoint from the widths of your own links. Then test it at 360px, at your breakpoint and at 200% zoom, and use only the keyboard to open and close the menu.
Expected result: Below the breakpoint, the toggle opens and closes the menu in a column, and aria-expanded changes with it. At or above the breakpoint, the links sit in one row and the toggle is hidden. The Tab key reaches every visible link and shows a focus outline.
S9. Next Steps and Community
Previous article: Flexbox Debugging, Browser Developer Tools and Best Practices.
Next article: Build a Responsive Card and Product Listing Layout.
Continue the series by using flexbox for another common part of almost every website: a set of cards and a product listing. The same ideas of free space, direction and mobile-first rules will carry over.
Try the examples in your own HTML and CSS project. Add a link, shorten the screen, and watch how the bar adapts. Share your navbar with the Upgradix community, and help other developers understand Flexbox through practical examples.
Build the bar. Stack it for small screens. Test it at every width.
Upgradix by Shrash Studio
Learn Technology. Build Your Future.
Quality Technology Education. Completely Free.