A CSS dropdown reveals a hidden submenu or action list when a visitor interacts with a trigger button or navigation link. Building dropdowns cleanly with position: relative on the wrapper, position: absolute on the menu panel, and :focus-within keeps layouts stable and supports keyboard navigation.
Anchor the dropdown list directly underneath its parent trigger using position: relative on .dropdown and position: absolute; top: 100%; left: 0; on .dropdown-menu. Using opacity + visibility + pointer-events: none (rather than display: none) allows smooth transitions while preventing accidental clicks when closed.
Pairing .dropdown:hover .dropdown-menu with .dropdown:focus-within .dropdown-menu ensures keyboard users tabbing into the trigger see the submenu open automatically.
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-trigger {
padding: 10px 16px;
background-color: #1e293b;
color: #ffffff;
border: none;
border-radius: 6px;
cursor: pointer;
}
.dropdown-menu {
position: absolute;
top: calc(100% + 6px);
left: 0;
min-width: 190px;
background-color: #ffffff;
border: 1px solid #cbd5e1;
border-radius: 8px;
padding: 6px;
box-shadow: 0 10px 25px rgba(15, 23, 42, 0.12);
opacity: 0;
visibility: hidden;
pointer-events: none;
transition: opacity 0.15s ease;
z-index: 30;
}
.dropdown:hover .dropdown-menu,
.dropdown:focus-within .dropdown-menu {
opacity: 1;
visibility: visible;
pointer-events: auto;
}
Notice a subtle trap: if there is an empty 6px gap between the button and .dropdown-menu, moving the mouse slowly downward leaves :hover and snaps the menu shut! Bridge the gap with transparent padding on a ::before pseudo-element, or trigger menus on click with JavaScript + aria-expanded for complex navigation.
:hover alone without :focus-within or click support: Touch screens and keyboard-only visitors cannot hover reliably.overflow: hidden on a parent header: Overflow clipping slices dropdown panels right at the navbar's bottom edge.z-index on the menu: Other cards further down the page may overlap behind or over your dropdown without z-index.Click-triggered menus (toggling aria-expanded in small JavaScript) are more reliable on touch devices and screen readers, while :hover + :focus-within works cleanly for quick CSS prototypes.
Replace left: 0; with right: 0; on .dropdown-menu when the button sits near the right edge of the viewport.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.