CSS
Responsive Navigation Bar with Flexbox Wrapping
Build a responsive navigation bar using Flexbox that automatically wraps menu items onto new lines as the viewport narrows, enhancing mobile usability.
/* HTML Structure: */
/* <nav class="navbar">
/* <a href="#" class="nav-brand">MyBrand</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; /* Pushes brand to one end, links to the other */
align-items: center;
background-color: #282c34;
padding: 10px 20px;
color: white;
}
.nav-brand {
font-size: 1.5em;
font-weight: bold;
color: white;
text-decoration: none;
margin-right: 20px;
flex-shrink: 0; /* Prevents brand from shrinking */
}
.nav-links {
display: flex;
flex-wrap: wrap; /* Links themselves can wrap if needed */
gap: 15px;
justify-content: flex-end; /* Aligns links to the right when there's space */
flex-grow: 1; /* Allows links section to take up available space */
}
.nav-links a {
color: white;
text-decoration: none;
padding: 5px 10px;
white-space: nowrap; /* Prevents individual link text from breaking */
}
.nav-links a:hover {
background-color: #61dafb;
border-radius: 4px;
}
How it works: This snippet creates a responsive navigation bar using Flexbox. The `.navbar` container is set to `display: flex;` and `flex-wrap: wrap;`, allowing its children (brand and nav links) to wrap onto multiple lines if the viewport is too narrow. `justify-content: space-between;` separates the brand from the navigation links. Inside `.nav-links`, another flex container is used with `flex-wrap: wrap;` and `gap` to manage the spacing and wrapping of individual links, ensuring a clean layout across different screen sizes. `flex-grow: 1` on `.nav-links` ensures it tries to take all available space to its right.