How to create a responsive navigation bar with CSS Flexbox

· Category: HTML & CSS

Short answer

Use CSS Flexbox with display: flex, justify-content: space-between, and align-items: center on the nav container. Add a media query to switch to a vertical layout on small screens, optionally toggling visibility with JavaScript.

Details

A responsive navigation bar starts with semantic HTML using the <nav> element and an unordered list for links. Apply display: flex to the <ul> to align items horizontally. Use gap for spacing instead of margins for cleaner code. For mobile, add a hamburger button and a media query that switches the list to flex-direction: column when the viewport is narrow.

You can enhance interactivity with JavaScript. For more on handling events efficiently, see How to debounce and throttle event handlers in JavaScript. If you are also working with form elements in your navigation (such as search inputs), you may find it useful to read about how to check data types in JavaScript accurately when validating user input.

Tips

  • Use flex-wrap: wrap if you have many nav items that might overflow on medium-sized screens.
  • Always include an aria-label or aria-labelledby on the <nav> element for screen reader users.
  • Test your nav with keyboard-only navigation to ensure all links are reachable.
  • For a deeper dive into organizing large stylesheets, see How to use CSS @layer to organize stylesheets.