CSS
Responsive Navigation Structure with CSS Grid and Hamburger Toggle
Design a flexible and responsive navigation bar using CSS Grid, including clear positioning for a main menu and a mobile hamburger toggle button.
.navbar {
display: grid;
grid-template-columns: auto 1fr auto; /* Logo, flexible space, toggle button */
align-items: center;
padding: 15px 20px;
background-color: #333;
color: white;
}
.navbar-logo {
font-weight: bold;
font-size: 1.2em;
}
.navbar-menu {
display: flex; /* Flexbox for menu items */
justify-content: flex-end; /* Align menu items to the right */
list-style: none;
margin: 0;
padding: 0;
}
.navbar-menu li a {
color: white;
text-decoration: none;
padding: 10px 15px;
display: block;
}
.hamburger-toggle {
display: none; /* Hidden by default on desktop */
cursor: pointer;
font-size: 1.5em;
background: none;
border: none;
color: white;
padding: 5px;
}
@media (max-width: 768px) {
.navbar {
grid-template-columns: auto 1fr; /* Logo, flexible space (toggle button below) */
grid-template-rows: auto auto; /* Two rows for logo/toggle and menu */
grid-template-areas:
"logo toggle"
"menu menu"; /* Menu spans full width on second row */
}
.navbar-logo {
grid-area: logo;
}
.hamburger-toggle {
grid-area: toggle;
display: block; /* Show hamburger on mobile */
justify-self: end; /* Push toggle to the right */
}
.navbar-menu {
grid-area: menu;
flex-direction: column; /* Stack menu items vertically */
display: none; /* Hidden by default on mobile, toggled by JS */
text-align: center;
width: 100%;
background-color: #444; /* Darker background for dropdown */
padding-top: 10px;
}
.navbar-menu.is-open { /* Class added by JS */
display: flex;
}
}
How it works: This snippet creates a responsive navigation bar using CSS Grid to structure its main components: a logo, the navigation menu, and a hamburger toggle button. On larger screens, the grid places these side-by-side. For smaller screens (via media query), the layout transforms: the logo and toggle button remain on the first row, and the navigation menu drops below, spanning the full width, ready to be toggled visible with JavaScript. Flexbox is used within the `navbar-menu` for its items.