CSS
Building a Responsive Flexbox Navigation Menu with Dynamic Spacing
Create an adaptable navigation bar that automatically spaces items and gracefully wraps to multiple lines on smaller screens using CSS Flexbox.
.navbar {
background-color: #007bff;
padding: 0.8rem 1rem;
display: flex;
flex-wrap: wrap; /* Allows items to wrap to next line */
justify-content: space-around; /* Distributes items with space around them */
align-items: center; /* Vertically centers items */
gap: 0.5rem; /* Space between flex items */
}
.navbar a {
color: white;
text-decoration: none;
padding: 0.5rem 1rem;
transition: background-color 0.3s ease;
border-radius: 4px;
white-space: nowrap; /* Prevent items from breaking words */
}
.navbar a:hover, .navbar a.active {
background-color: #0056b3;
}
/* Adjustments for very small screens if needed, though flex-wrap handles most */
@media (max-width: 480px) {
.navbar {
justify-content: center; /* Center items when stacked */
}
}
How it works: This snippet creates a responsive navigation menu using Flexbox. The `.navbar` container uses `display: flex` and `flex-wrap: wrap` to allow navigation links to flow onto new lines if there isn't enough space. `justify-content: space-around` ensures items are dynamically spaced, and `align-items: center` keeps them vertically aligned. The `gap` property provides consistent spacing between menu items.