CSS
Create a Responsive Navigation Bar with Flexbox and Gap
Design a flexible navigation menu that automatically spaces items and stacks vertically on smaller screens, leveraging Flexbox properties like `justify-content` and the `gap` property for spacing.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Nav with Flexbox</title>
<style>
body {
font-family: sans-serif;
margin: 0;
}
.navbar {
background-color: #4CAF50;
padding: 10px 20px;
display: flex;
justify-content: space-between; /* Distribute items */
align-items: center;
flex-wrap: wrap; /* Allow items to wrap */
gap: 20px; /* Space between flex items */
}
.navbar-brand {
color: white;
font-size: 24px;
text-decoration: none;
font-weight: bold;
}
.nav-menu {
display: flex;
list-style: none;
margin: 0;
padding: 0;
gap: 15px; /* Space between menu items */
}
.nav-menu li a {
color: white;
text-decoration: none;
padding: 8px 15px;
border-radius: 5px;
transition: background-color 0.3s ease;
}
.nav-menu li a:hover {
background-color: #5cb85c;
}
/* Responsive behavior */
@media (max-width: 600px) {
.navbar {
flex-direction: column; /* Stack vertically */
align-items: flex-start; /* Align brand and menu to start */
}
.nav-menu {
flex-direction: column; /* Stack menu items vertically */
width: 100%; /* Take full width */
margin-top: 10px;
gap: 5px; /* Adjust gap for vertical stacking */
}
.nav-menu li {
width: 100%;
}
.nav-menu li a {
display: block; /* Make links block level */
text-align: center;
background-color: rgba(255, 255, 255, 0.1);
}
.nav-menu li a:hover {
background-color: rgba(255, 255, 255, 0.2);
}
}
</style>
</head>
<body>
<nav class="navbar">
<a href="#" class="navbar-brand">Brand</a>
<ul class="nav-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>
<div style="padding: 20px;">
<h2>Page Content</h2>
<p>Resize your browser to see the responsive navigation in action.</p>
<p>The navigation bar uses Flexbox to distribute items horizontally on larger screens and stacks them vertically on smaller screens, demonstrating a common responsive pattern.</p>
</div>
</body>
</html>
How it works: This snippet creates a responsive navigation bar using Flexbox. It uses `display: flex`, `justify-content: space-between` to separate the brand and menu, and `gap` for consistent spacing between items. A media query transforms the layout into a vertical stack on smaller screens by changing `flex-direction` to `column` and adjusting alignment, making the navigation adaptable to different device sizes.