DEV Community

eitanwaxman
eitanwaxman

Posted on

Toggling Without JS - Buttons Reimagined 🀯

The story begins with wanting to recreate the "hamburger menu that animates into an X" that is quite popular these days. Oh and only using CSS.

At first I tried to tap into the :focus pseudo class to control the changes. Something like this:

button{
...
}

//top line
button::after{
...
}

//bottom line
button::before{
...
}

button:focus::before{
transform: rotate(45deg);
}

etc...
Enter fullscreen mode Exit fullscreen mode

The problem was that it couldn't be reverted back to the initial state by clicking on the button again. Only clicking outside the button could remove the focus.

Then while watching a tutorial by my fav YouTube developer Web Dev Simplified it hit me. What about using a checkbox input instead of a button to manage the toggle?

An hour or two later I arrived at this:

I made some tweaks to the method such as using absolute and width: 0 to disappear the input but the overall concept is the same.

This CSS magic kinda makes the checkbox type input the king of JS-less state. I decided to take it one step further. Could we implement an effect as well -such as the dropdown of the actual menu?

After much struggle I can say the answer is - sort of.

The checkbox/toggle can affect other elements as long as they are within CSS reach. The elements must be at the same level as the toggle and share a parent.

All this jumping through hoops made me wonder - why isn't there a toggle pseudo class? Are there any other ways to implement toggle in CSS? Is this actually worthwhile and scalable?

lmk ✌

Top comments (0)