CSS
Flexbox: Responsive Navigation Menu with Item Wrapping
Build a flexible navigation menu that wraps items onto new lines using `flex-wrap` and adapts beautifully across different screen sizes with media queries.
.nav-menu {
display: flex;
flex-wrap: wrap; /* Allow items to wrap to the next line */
justify-content: flex-start; /* Start items from the left */
list-style: none;
padding: 0;
margin: 0;
background-color: #333;
}
.nav-menu li {
margin: 0 10px;
}
.nav-menu a {
display: block;
padding: 15px 20px;
color: white;
text-decoration: none;
white-space: nowrap; /* Prevent individual links from breaking */
}
@media (max-width: 768px) {
.nav-menu {
justify-content: center; /* Center items when they wrap */
}
.nav-menu li {
width: 100%; /* Make each item take full width */
text-align: center;
margin: 0;
}
.nav-menu a {
border-bottom: 1px solid #555;
}
.nav-menu li:last-child a {
border-bottom: none;
}
}
How it works: This snippet creates a responsive navigation menu using Flexbox. By default, items are laid out horizontally. The `flex-wrap: wrap` property allows navigation items to flow onto the next line if the container is too narrow. A media query then targets smaller screens, making each menu item take up the full width, effectively turning the horizontal menu into a vertical one suitable for mobile viewports.