The infamous radio button hack
Lots has been written already about the "radio button hack" and I'm here to tell you that it isn't - it's not a hack, because you're not exploiting any loopholes or functionality that may or may not be fixed down the line - the radio button trick works and should keep on working for the foreseeable future; that and the checkbox trick. What's it about then?
The basic premise is that you can use radio
buttons to select one element out of a group and use the state of the selected element to target/style another - you can also use a checkbox
if you're only interested in changing the state of one element. The technique relies on 3 things:
- The active state of a radio button or checkbox
- The label for that element as the trigger
- Using sibling selectors to target a corresponding container
WAT!!!???
The active state of a radio button or checkbox …
A set of radio buttons is associated via the name
attribute and you can only select one in a group - e.g.:
… will give you the below. Notice how only one radio
button can be active at a time in either of the groups (also notice how the default state for all radio buttons is OFF/not checked) - this applies to all radio buttons in a document that are in the same group, irrespective of where in the document they are placed …
… which is useful for forms and stuff (think multiple choice questions), but we can also use that to change the properties of elements elsewhere in our document.
The label for that element as the trigger …
Notice how I specify which <label></label>
belongs to which radio
button by means of the for and id attributes? Radio buttons are ugly and we cannot style them, but their labels are useful for just that and can carry ::before
and ::after
pseudo elements.
Using sibling selectors to target a corresponding container …
So we've already used one sibling selector (adjacent sibling using + ) to target the labels following an active radio button, but this is not entirely useful as we might want to target an element later in the same document using the same trick … enters the general sibling selector ( ~
) …
The main thing to remember is that, for an element to be adjacent to another, they have to be direct descendants of the same parent container …
… and we can use this trick like this …
A simple enough trick - I'll be using this lots in future posts … stay tuned - also: comments are open, play nice.
Notes on use:
These sibling selector have been around for a while now, so browser support is generally very good … i.e. don't be shy to use them.