CSS Animation Example: Hamburger to X
The "Hamburger to X" transformation has become the standard micro-interaction for mobile menus, clearly indicating when a menu is open and how to close it.
This effect relies on CSS transitions applied to three separate lines (usually div or span elements) stacked vertically. When an .open class is toggled on the parent button button (often via JavaScript), we use transform: translateY() rotate() to move the top and bottom lines to the center and angle them 45 degrees in opposite directions, forming an 'X'. Concurrently, we fade out the middle line.
Here is the code to create the Hamburger to X animation.
Accessibility Considerations
Because this animation purely provides visual flair and doesn't communicate state that isn't already obvious from the icon's finalized position, we can safely disable the smooth transition using the prefers-reduced-motion media query. prefers-reduced-motion is a CSS media feature used to detect if a user has enabled a setting on their device to minimize the amount of non-essential animation or motion. This way, the icon snaps instantly from a hamburger to an X for users who prefer reduced motion.
Here's what we used in our example:
@media (prefers-reduced-motion: reduce) {
.hamburger-line {
/* Remove the smooth transition, causing it to snap instantly */
transition: none;
}
}