web 2 min
Toggle something on a web page without JS
The label + checkbox + :checked + ~ selector trick. State in pure CSS, learned from Travis Neilson.
If you are gaining experience in CSS and trying the limits of CSS, this trick will make you think CSS is more powerful than ever before. Some years ago I learned this trick from Travis Neilson in this video.
We all know how you can use transitions and hover to change the state of an element to create some interactivity. What if I told you that you can make it toggle instead of temporarily changing state?
Labels and inputs
To understand this trick, first thing you should know is that <input> tags are bound to their labels with id and for attributes.
Let’s say you have a text input with id="mytext", when you click on a <label> with for="mytext" it behaves as if you clicked the <input>.
Checkbox
So in our case we will be using an <input> with type="checkbox" to toggle stuff. And the toggler will be a <label> with for="[id of input]".
:checked state
In CSS we have a pseudo-class :checked. It applies some styles only when an <input type="checkbox"> is checked. This allows us to apply some styles with permanent states not only to <input> itself, but also its siblings and children.
However <input> tags can’t have any children. Here we use this CSS selector to enhance our selection: ~.
~ Selector
~ Selector selects an element only when it has a matching sibling before it.
For example if we had HTML like this:
<div>
<div class="key">key</div>
<div></div>
<div></div>
<div class="lock">lock</div>
</div>
<div>
<div></div>
<div></div>
<div></div>
<div class="lock">lock</div>
</div>
We could select only the first <div> with class “lock” with this selector.
.key~.lock{
color: red;
}
See example here:
Once we select an element after some sibling, we can also select children of the selection, which is handy because we can make this our main wrapper on the page and toggle any styles on our page with this stateful selector.
Here is an example on CodePen demonstrating it:
Also you can go wild with it like in the example below:
If you check the above example’s code, you will see the HTML is a bit of a soup.
You would probably use this trick only for navigation sidebars, modals, etc.