Sub topic 3
Keep a Navigation Bar Visible and Responsive
Assume you know basic HTML, CSS selectors, and the box model. This chapter adds sticky positioning, custom properties, dropdowns, and a mobile menu.
Keep the bar visible with `position: sticky`
position: sticky keeps an element in normal document flow until it reaches a specified edge. Then it remains there while its scroll container continues moving.
Use top: 0 to attach the bar to the viewport’s top edge. A z-index places it above content that scrolls underneath it.
Centralize colors and spacing with custom properties
CSS custom properties are named values that you can reuse. Define them on :root, then read them with var().
:root {
--nav-bg: #1f2937;
--nav-hover: #374151;
--nav-active: #111827;
--nav-focus: #38bdf8;
--nav-space: 0.75rem 1rem;
}
nav {
position: sticky;
top: 0;
z-index: 10;
background: var(--nav-bg);
}Add a dropdown submenu
Place a nested list inside its parent list item. Make the parent the positioning context. The submenu can open on pointer hover or when keyboard focus enters it.
.has-submenu {
position: relative;
}
.submenu {
display: none;
position: absolute;
top: 100%;
left: 0;
min-width: 12rem;
margin: 0;
padding: 0;
list-style: none;
background: var(--nav-bg);
}
.has-submenu:hover > .submenu,
.has-submenu:focus-within > .submenu {
display: block;
}focus-within keeps the submenu visible while a keyboard user moves between its links.
Adapt the layout to small screens
A horizontal bar may not fit on a narrow screen. Use a media query to stack links and hide them until the user opens the menu.
@media (max-width: 40rem) {
.nav-list {
display: none;
flex-direction: column;
}
.nav-list.is-open {
display: flex;
}
}Add a mobile menu toggle button
Use a real button, not a clickable div. aria-controls identifies the list, and aria-expanded communicates its state to assistive technology.
<button class="nav-toggle" aria-expanded="false" aria-controls="nav-list">
Menu
</button>
<ul class="nav-list" id="nav-list">
<li><a href="/">Home</a></li>
<li><a href="/products">Products</a></li>
</ul>
<script>
const toggle = document.querySelector(".nav-toggle");
const list = document.querySelector("#nav-list");
toggle.addEventListener("click", () => {
const open = toggle.getAttribute("aria-expanded") === "true";
toggle.setAttribute("aria-expanded", String(!open));
list.classList.toggle("is-open", !open);
});
</script>Keep the attribute and class synchronized. Otherwise, the visual state and the state announced by a screen reader can disagree.
Exercise
Why does the submenu use both :hover and :focus-within?
Show answer
Hover supports pointer users, while :focus-within keeps the submenu usable when someone navigates with a keyboard.