CSS
Responsive Flexbox Navigation
Build a flexible and responsive navigation bar that adapts gracefully across different screen sizes using CSS Flexbox, ideal for modern web design.
.navbar {
display: flex;
justify-content: space-between; /* Pushes items to ends, spaces in between */
align-items: center; /* Vertically centers items */
background-color: #333;
padding: 10px 20px;
color: white;
}
.navbar-brand {
font-weight: bold;
font-size: 1.5em;
}
.navbar-nav {
display: flex;
list-style: none;
margin: 0;
padding: 0;
}
.navbar-nav li {
margin-left: 20px;
}
.navbar-nav a {
color: white;
text-decoration: none;
}
/* For smaller screens, stack items */
@media (max-width: 768px) {
.navbar {
flex-direction: column; /* Stack items vertically */
align-items: flex-start; /* Align items to the start */
}
.navbar-nav {
flex-direction: column;
width: 100%;
margin-top: 10px;
}
.navbar-nav li {
margin-left: 0;
margin-bottom: 10px;
}
}
How it works: This snippet creates a responsive navigation bar using Flexbox. On larger screens, `justify-content: space-between` distributes the brand and navigation links horizontally. A media query is then used to transform the layout for smaller screens by changing `flex-direction` to `column` for both the main navbar and the navigation links. This stacks elements vertically, ensuring optimal readability and usability on mobile devices.