← Back to all snippets
CSS

Responsive Navigation Bar: Stacking and Spreading with Flexbox

Craft a dynamic navigation bar that fluidly transitions from a vertical stack on small screens to a horizontal, evenly distributed layout on larger displays, leveraging Flexbox properties for seamless responsiveness.

.nav-bar {
    display: flex;
    flex-direction: column; /* Stacked by default for mobile */
    list-style: none;
    padding: 0;
    margin: 0;
    background-color: #333;
}

.nav-bar li a {
    display: block;
    padding: 10px 15px;
    color: white;
    text-decoration: none;
    text-align: center;
    border-bottom: 1px solid #555; /* Separator for stacked items */
}

.nav-bar li:last-child a {
    border-bottom: none;
}

@media (min-width: 768px) {
    .nav-bar {
        flex-direction: row; /* Horizontal on larger screens */
        justify-content: space-around; /* Distribute items evenly */
        border-bottom: none; /* Remove separator */
    }

    .nav-bar li a {
        border-bottom: none; /* Remove separator */
    }
}
How it works: This snippet creates a responsive navigation bar using Flexbox. By default, `flex-direction: column` stacks menu items vertically, ideal for mobile devices. A media query then switches `flex-direction` to `row` for wider screens, making items horizontal. `justify-content: space-around` ensures items are evenly distributed, adapting the navigation's layout based on viewport size. The HTML should consist of a `<nav>` element containing a `<ul>` with class `nav-bar`, and `<li>` items inside.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs