📚 Theory: CSS-Only Hamburger Menu

What Is the "Checkbox Hack"?

You can create interactive components using only CSS by combining a hidden checkbox with the :checked pseudo-class. When the checkbox is checked, you show the menu. When unchecked, you hide it.

How It Works

Real-World Examples

Why Learn This?

Limitations (Why Real Sites Use JavaScript)

CSS-Only Hamburger Menu

Click the ☰ icon above to open and close the mobile menu.

No JavaScript was used. This menu works entirely with CSS using the :checked pseudo-class.

On desktop (768px and above), the hamburger disappears and the navigation becomes a horizontal row.

/* =================================== STEP 1: HIDE THE CHECKBOX =================================== */ #menu-toggle { display: none; } /* =================================== STEP 2: HIDE THE MENU BY DEFAULT =================================== */ .nav-menu { display: none; position: absolute; top: 100%; left: 0; right: 0; background-color: #0f3460; flex-direction: column; padding: 20px; } /* =================================== STEP 3: SHOW MENU WHEN CHECKBOX IS CHECKED =================================== */ #menu-toggle:checked ~ .nav-menu { display: flex; } /* =================================== STEP 4: ON DESKTOP, ALWAYS SHOW MENU =================================== */ @media (min-width: 768px) { .hamburger { display: none; /* Hide hamburger */ } .nav-menu { display: flex; /* Always show menu */ position: static; flex-direction: row; } }

🔧 The :checked Pseudo-Class

What Else Can You Do With :checked?

The Sibling Selector (~)

Notice the ~ (tilde) in #menu-toggle:checked ~ .nav-menu.

The general sibling selector (~) selects all siblings after an element. In this case, it selects the .nav-menu that comes after the checkbox.

/* General sibling selector - selects ALL siblings after */ #menu-toggle:checked ~ .nav-menu { } /* Adjacent sibling selector - selects ONLY the immediate next sibling */ #menu-toggle:checked + .nav-menu { }

Real-World Use: Custom Checkbox

/* Hide default checkbox */ input[type="checkbox"] { display: none; } /* Create custom checkbox */ .custom-checkbox { display: inline-block; width: 20px; height: 20px; background-color: white; border: 2px solid #ccc; border-radius: 4px; } /* When checked, change appearance */ input[type="checkbox"]:checked + .custom-checkbox { background-color: #4a90e2; border-color: #4a90e2; }