Reputation: 11973
Taking an example from the end of https://developer.mozilla.org/en-US/docs/Learn/Forms/How_to_build_custom_form_controls:
.select label {
display: none;
}
.select:focus-within label {
display: initial;
}
input:checked + label {
display: initial;
}
<fieldset class="select">
<legend>Pick a fruit</legend>
<input type="radio" name="fruit" value="Cherry" id="fruitCherry" checked>
<label for="fruitCherry">Cherry</label>
<input type="radio" name="fruit" value="Lemon" id="fruitLemon">
<label for="fruitLemon">Lemon</label>
<input type="radio" name="fruit" value="Banana" id="fruitBanana">
<label for="fruitBanana">Banana</label>
</fieldset>
(I have simplified the example to better illustrate the point). Note how you can click on one of the labels, and since focus is inside the select after that, all labels become visible. However, as soon as you try to click on label of another item, the labels disappear before selecting that item, since there is a brief period before the mouse button is released where no element is focused. I assume the the browser only handles the click event when the mouse button is released.
Is there any way to keep the focus while holding down the mouse button as well, without JavaScript? I experienced this on Firefox and Chrome on Linux.
I am also surprised by the fact that it acts differently depending on whether you click-and-hold on the label or the radio button.
Upvotes: 1
Views: 183
Reputation:
By default
<label>
is not a focusable Element.
When you try to click a label it's as if you're clicking away to remove the focus from what you previously clicked.
In order to make an element focusable we use the tabindex
attribute with a negative value so it doesn't interfere with the navigation because our sole purpose is to make the element focusable
.select label {
display: none;
}
.select:focus-within label {
display: initial;
}
input:checked+label {
display: initial;
}
<fieldset class="select">
<legend>Pick a fruit</legend>
<input type="radio" name="fruit" value="Cherry" id="fruitCherry" checked>
<label tabindex="-1" for="fruitCherry">Cherry</label>
<input type="radio" name="fruit" value="Lemon" id="fruitLemon">
<label tabindex="-1" for="fruitLemon">Lemon</label>
<input type="radio" name="fruit" value="Banana" id="fruitBanana">
<label tabindex="-1" for="fruitBanana">Banana</label>
</fieldset>
Upvotes: 1