CSS
Responsive Navigation Bar with Flexbox Item Distribution
Create a flexible navigation bar that effectively distributes space among its items, aligning some to the start and others to the end, and adapts gracefully to different screen sizes.
.navbar {
display: flex;
justify-content: space-between; /* Pushes first and last item to edges, spaces others evenly */
align-items: center; /* Vertically centers items */
background-color: #333;
padding: 10px 20px;
color: white;
flex-wrap: wrap; /* Allow items to wrap on smaller screens */
}
.navbar-brand {
margin-right: auto; /* Pushes the brand to the left, and other items to the right */
font-size: 1.5em;
font-weight: bold;
flex-shrink: 0; /* Prevent brand from shrinking */
}
.navbar-menu {
display: flex;
list-style: none;
margin: 0;
padding: 0;
flex-grow: 1; /* Allow menu to grow and take available space */
justify-content: flex-end; /* Align menu items to the end by default */
}
.navbar-menu li {
margin-left: 20px;
}
.navbar-menu a {
color: white;
text-decoration: none;
padding: 5px 0;
display: block;
}
/* Basic responsiveness for smaller screens */
@media (max-width: 600px) {
.navbar {
flex-direction: column; /* Stack items vertically */
align-items: flex-start; /* Align items to the start when stacked */
padding: 15px;
}
.navbar-brand {
margin-right: 0;
margin-bottom: 10px;
}
.navbar-menu {
flex-direction: column;
align-items: flex-start;
width: 100%;
margin-top: 10px;
border-top: 1px solid rgba(255,255,255,0.1);
padding-top: 10px;
}
.navbar-menu li {
margin-left: 0;
margin-bottom: 8px;
width: 100%;
}
.navbar-menu a {
padding: 8px 0;
border-radius: 4px;
transition: background-color 0.3s ease;
}
.navbar-menu a:hover {
background-color: rgba(255,255,255,0.1);
}
}
/* --- HTML Structure --- */
<nav class="navbar">
<div class="navbar-brand">MyBrand</div>
<ul class="navbar-menu">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
How it works: This snippet creates a responsive navigation bar using Flexbox. The `.navbar` container uses `display: flex`, `justify-content: space-between` to push items to the edges (brand left, menu right), and `align-items: center` for vertical alignment. `flex-wrap: wrap` allows items to move to a new line on smaller screens. `margin-right: auto` on `.navbar-brand` pushes subsequent items to the right. The `.navbar-menu` also uses flexbox to arrange its items. A media query then transforms the layout into a vertical stack for mobile devices.