Zed A. Shaw, Writer Profile picture
Learn to code at https://t.co/M2PoncbFO6. I stream programming, games, and teach art at https://t.co/a41VlARoyB every day.

Jul 20, 2021, 11 tweets

I'll use this to do a running commentary on a "style checkbox" in CSS. First trick is to put the label *after* the checkbox so you can use + to select it if the checkbox is :checked. Clicking the label activates the hidden input, so the label changes red/green.

Here's a demo of that first part working. Now to make the label look like a checked/unchecked box that's different.

The next trick is to use the :after to add content, *but* if you give an :after that has no content it still creates a block you can style. Here I'm just making a little square.

Then in the main label we set it to display:flex, align-items: center, and give it a bit of padding on the left and right. Now we have a little box that's sitting on the left. We then need it to move to the right when the checkbox is checked.

To do that we just add flex-direction: row-reverse so the contents of the label (aka the :after box) are drawn in reverse order. Put that in the :checked rule and now you have a little box that toggles sides when you click it.

Finally, you change the background to indicate checked/unchecked. This is sort of where I think it falls apart as a UI element. It's hard to make a difference between "unchecked" and "disabled", and I don't think it's that clear you can click on it to change it.

Here's a demo of what that looks like. I think next level is to allow for two blocks of text for checked/unchecked states.

Well that's not too hard. First make two children for the <active> and <inactive> displays. Then, a series of :checked and regular rules that show/hide those depending on the state. Finally, set justify-content to space-between to push them to either side and done.

Here's the demo for that. I wonder if I can throw some Icons in there?

And with a bunch of little minor changes we have this code for what I think is a full feature Switch:

git.learnjsthehardway.com/zedshaw/zedsha…

Even has different sized variants, allows Icons, changes the font size, etc.

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling