CSS
Build a Responsive Navigation Bar with CSS Flexbox
Create a flexible and responsive navigation bar that adapts gracefully to different screen sizes, utilizing Flexbox properties like `justify-content` and `flex-wrap`.
/* HTML Structure Example: */
/*
<nav class="navbar">
<a href="#" class="brand">MySite</a>
<ul class="nav-links">
<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>
*/
.navbar {
display: flex;
justify-content: space-between; /* Pushes brand to one side, links to other */
align-items: center; /* Vertically aligns items */
background-color: #3498db;
padding: 1rem 1.5rem;
color: white;
flex-wrap: wrap; /* Allows items to wrap onto the next line if space is limited */
}
.brand {
font-size: 1.8rem;
font-weight: bold;
color: white;
text-decoration: none;
margin-right: 1rem; /* Space between brand and links if they are on same line */
}
.nav-links {
list-style: none;
margin: 0;
padding: 0;
display: flex;
gap: 1.5rem; /* Space between navigation items */
flex-wrap: wrap; /* Allows individual links to wrap within the list */
}
.nav-links li a {
color: white;
text-decoration: none;
padding: 0.5rem 0;
transition: color 0.3s ease;
}
.nav-links li a:hover {
color: #ecf0f1;
}
/* Media query for smaller screens: stack elements */
@media (max-width: 600px) {
.navbar {
flex-direction: column; /* Stack brand and links vertically */
align-items: flex-start; /* Align all items to the start */
}
.brand {
margin-bottom: 1rem;
margin-right: 0;
}
.nav-links {
width: 100%; /* Make links take full width when stacked */
flex-direction: column;
gap: 0.5rem;
}
.nav-links li {
width: 100%;
}
.nav-links li a {
display: block; /* Make links block-level for easier clicking */
padding: 0.75rem 0;
background-color: rgba(255, 255, 255, 0.1);
text-align: center;
border-radius: 44px;
}
}
How it works: This snippet provides a robust solution for a responsive navigation bar using CSS Flexbox. The `.navbar` container uses `display: flex` and `justify-content: space-between` to separate the brand from the navigation links. `align-items: center` keeps them vertically aligned. Crucially, `flex-wrap: wrap` allows elements to move to the next line if the viewport narrows. A media query further enhances responsiveness by stacking the brand and links vertically using `flex-direction: column` on smaller screens, creating a mobile-friendly menu layout.