CSS
Responsive Flexbox Navigation with 'flex-grow' and 'flex-shrink'
Create a responsive navigation bar using Flexbox's 'flex-grow' and 'flex-shrink' properties to distribute space and manage item sizing effectively.
.navbar {
display: flex;
flex-wrap: wrap;
list-style: none;
padding: 0;
margin: 0;
background-color: #333;
}
.navbar-item {
flex-grow: 1; /* Allows items to grow to fill space */
flex-shrink: 1; /* Allows items to shrink if space is limited */
flex-basis: 0; /* Ensures even distribution when growing */
text-align: center;
padding: 15px 0;
color: white;
text-decoration: none;
border-right: 1px solid #555;
}
.navbar-item:last-child {
border-right: none;
}
@media (max-width: 600px) {
.navbar-item {
flex-basis: 100%; /* Items stack on small screens */
border-right: none;
border-bottom: 1px solid #555;
}
.navbar-item:last-child {
border-bottom: none;
}
}
How it works: This snippet demonstrates how to build a responsive navigation bar using Flexbox. By setting `flex-grow: 1` and `flex-shrink: 1` with `flex-basis: 0`, the navigation items will evenly distribute available space on larger screens. On smaller screens, a media query changes `flex-basis` to `100%`, causing the items to stack vertically, providing a clean mobile experience without needing complex JavaScript.