CSS

Responsive Flexbox Navigation Bar with Dynamic Item Sizing and Spacing

Build a flexible navigation bar using CSS Flexbox, allowing navigation items to automatically adjust their width and spacing, adapting to various content lengths and screen sizes.

.navbar {
    display: flex;
    flex-wrap: wrap; /* Allows items to wrap onto the next line */
    justify-content: space-between; /* Distributes items and space */
    align-items: center; /* Vertically centers items */
    background-color: #4CAF50;
    padding: 0.5rem 1rem;
    gap: 0.8rem; /* Space between flex items */
}

.navbar-item {
    flex: 1 1 auto; /* Allows items to grow, shrink, and have an initial auto basis */
    min-width: 80px; /* Minimum width for small items */
    padding: 0.5rem 1rem;
    text-align: center;
    background-color: #66bb6a;
    color: white;
    text-decoration: none;
    border-radius: 5px;
    transition: background-color 0.3s ease;
}

.navbar-item:hover {
    background-color: #81c784;
}

/* Media query for smaller screens where items might stack */
@media (max-width: 600px) {
    .navbar-item {
        flex: 1 1 100%; /* Items take full width on small screens */
        min-width: unset; /* Remove min-width when stacking */
    }
}

/* <!-- HTML STRUCTURE --> */
<nav class="navbar">
    <a href="#" class="navbar-item">Home</a>
    <a href="#" class="navbar-item">About Us</a>
    <a href="#" class="navbar-item">Services</a>
    <a href="#" class="navbar-item">Contact</a>
    <a href="#" class="navbar-item">A Long Nav Item Name</a>
</nav>
How it works: This snippet creates a responsive navigation bar using Flexbox. `display: flex` initializes the flex container. `flex-wrap: wrap` allows items to move to the next line on smaller screens. `justify-content: space-between` distributes items with space between them, while `align-items: center` ensures vertical alignment. The `flex: 1 1 auto` on `navbar-item` makes them grow and shrink, taking up available space. `gap` provides consistent spacing. A media query adjusts items to stack vertically on small screens for better readability.

Need help integrating this into your project?

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

Hire DigitalCodeLabs