Horizontal Navigation Bar
You'll learn how to build a clean, responsive horizontal navigation menu using flexbox to evenly distribute links and align them properly.
What It Is
A horizontal navigation bar is one of the most common UI patterns on the web—think of the menu links across the top of almost every website. Flexbox makes building these incredibly straightforward: it automatically spaces items evenly, handles alignment, and adapts to different screen sizes without complex calculations.
The Pattern
The typical structure is a <nav> container with a list of links inside. By applying display: flex to the container, all links become flex items that you can distribute and align along the main (horizontal) axis.
Here's the common approach:
nav {
display: flex;
justify-content: space-between; /* or space-around, space-evenly */
align-items: center;
gap: 1rem; /* modern spacing between links */
padding: 1rem 2rem;
background-color: #333;
}
nav a {
color: white;
text-decoration: none;
padding: 0.5rem 1rem;
}
Think of it like guests at a dinner table: justify-content: space-between puts maximum space between each guest, while space-evenly ensures equal gaps everywhere (including the ends). The align-items: center keeps everything vertically centered, even if some links have different heights.
You can also use flex-grow on specific items (like a logo) to push other links to the right, or margin-left: auto on a link to create a "right-aligned" section within the same nav bar.
Key Takeaway: Flexbox turns navigation bars from a positioning puzzle into a few simple properties—use display: flex, justify-content for spacing, and align-items for vertical alignment to create professional horizontal menus effortlessly.