← Back to all snippets
CSS

Responsive Navigation Menu with Flexbox Wrapping

Learn to create a flexible, responsive navigation menu that automatically wraps items to the next line when space is limited, ensuring optimal display across devices using CSS Flexbox.

/* HTML Structure for context:
<nav class="navbar">
    <a href="#" class="navbar-brand">Brand</a>
    <div class="nav-links">
        <a href="#">Home</a>
        <a href="#">About</a>
        <a href="#">Services</a>
        <a href="#">Contact</a>
    </div>
</nav>
*/

.navbar {
    display: flex;
    flex-wrap: wrap; /* Allows items to wrap onto the next line */
    justify-content: space-between; /* Distributes brand and links */
    align-items: center; /* Vertically centers items */
    background-color: #333;
    padding: 10px 20px;
    color: white;
}

.navbar-brand {
    font-weight: bold;
    font-size: 1.5em;
    margin-right: 20px; /* Space from links when not wrapped */
    flex-shrink: 0; /* Prevent brand from shrinking too much */
    color: inherit;
    text-decoration: none;
}

.nav-links {
    display: flex;
    flex-wrap: wrap; /* Allows individual links to wrap within their container */
    gap: 15px; /* Space between links */
    flex-grow: 1; /* Allows links to take up available space */
    justify-content: flex-end; /* Align links to the right by default */
}

.nav-links a {
    color: white;
    text-decoration: none;
    padding: 5px 0;
    white-space: nowrap; /* Prevent individual links from breaking */
}

/* Example of how it might look on smaller screens */
@media (max-width: 600px) {
    .navbar {
        justify-content: center; /* Center items on small screens if they wrap */
        padding: 15px;
    }

    .navbar-brand {
        margin-right: 0;
        margin-bottom: 10px; /* Space below brand when it's on its own line */
        width: 100%; /* Brand takes full width */
        text-align: center;
    }

    .nav-links {
        justify-content: center; /* Center links when they wrap below the brand */
        width: 100%; /* Links take full width */
    }
}
How it works: This CSS Flexbox snippet creates a responsive navigation menu. The `flex-wrap: wrap` property on both the main `.navbar` and `.nav-links` container allows items to flow onto new lines when the viewport narrows, preventing overflow. `justify-content: space-between` initially separates the brand and navigation links, while media queries adjust positioning (e.g., `justify-content: center`) for smaller screens, ensuring readability and usability across different device sizes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs