:: krowemoh

Friday | 27 DEC 2024
Posts Links Other About Now

previous
next

Checkbox Hack to Hide and Show Elements

2022-01-25

This will be a simple blog post. Many times I want to do some sort of toggle of hiding and showing elements on click and I can do this without javascript. The longer I go without having to write javascript, the better in my eyes! When I do need to write it, then it means hopefully that I have a real reason to.

The logic of the checkbox hack is that CSS can be styled conditionally based on if a checkbox is ticked or not.

We need three things in the html, we need a label, the checkbox and the element we are going to be toggling.

<label for="season-dropdown" class="dropdown flex-center">Season 1</label>
<input type="checkbox" id="season-dropdown" class="hide">
<div class="dropdown-container">
</div>

We give the checkbox an id and then we set up a label for it so now by clicking the label the checkbox will be toggled. Then we can write the CSS like below:

.dropdown-container { display: none; };
#season-dropdown ~ .dropdown-container { display: block; }

With that we can now conditionally display the dropdown container by using the label.

This is a simple and effective way of toggling things into view though the CSS does get a bit hairy if you start trying to do this with a lot of things. I'm also curious if there is a performance loss relying on CSS like this.