← Back to all snippets
CSS

Flexbox: Responsive Navigation Bar with `flex-wrap`

Build a robust and responsive navigation bar using CSS Flexbox, allowing menu items to wrap or adjust spacing based on screen size.

.navbar {
    display: flex;
    flex-wrap: wrap; /* Allows items to wrap onto the next line */
    justify-content: space-between; /* Spreads items evenly with space between */
    align-items: center; /* Vertically aligns items */
    background-color: #343a40;
    padding: 10px 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.navbar-brand {
    color: white;
    font-size: 1.5em;
    font-weight: bold;
    text-decoration: none;
    margin-right: 20px;
}

.navbar-menu {
    display: flex;
    flex-wrap: wrap;
    list-style: none;
    margin: 0;
    padding: 0;
}

.navbar-item {
    margin-left: 15px; /* Spacing between menu items */
}

.navbar-item a {
    color: #adb5bd;
    text-decoration: none;
    padding: 5px 10px;
    transition: color 0.3s ease;
}

.navbar-item a:hover {
    color: white;
}

/* Adjustments for smaller screens if needed (e.g., stacking brand and menu) */
@media (max-width: 600px) {
    .navbar {
        flex-direction: column; /* Stacks brand and menu vertically */
        justify-content: center;
    }
    .navbar-brand {
        margin-bottom: 10px;
        margin-right: 0;
    }
    .navbar-menu {
        width: 100%; /* Ensure menu takes full width */
        justify-content: center; /* Center menu items */
        margin-top: 10px;
    }
    .navbar-item {
        margin: 0 10px 10px; /* Adjust item spacing for stacked layout */
    }
}

<!-- HTML -->
<nav class="navbar">
    <a href="#" class="navbar-brand">MySite</a>
    <ul class="navbar-menu">
        <li class="navbar-item"><a href="#">Home</a></li>
        <li class="navbar-item"><a href="#">About</a></li>
        <li class="navbar-item"><a href="#">Services</a></li>
        <li class="navbar-item"><a href="#">Contact</a></li>
    </ul>
</nav>
How it works: This snippet provides a flexible and responsive navigation bar using Flexbox. The `.navbar` container uses `display: flex` and `flex-wrap: wrap` to allow navigation items to flow onto new lines if space becomes limited. `justify-content: space-between` places the brand on one end and the menu on the other. For smaller screens, a media query changes `flex-direction` to `column` on the main navbar and adjusts `justify-content` on the menu to center items, creating a stacked, mobile-friendly layout.

Need help integrating this into your project?

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

Hire DigitalCodeLabs