As mentioned in arieljuod's comment above, <input>
elements of type radio work as you describe. You can define a radio group by "giving each of [the] radio buttons in the group the same name
."
If you are not limited to using <button>
, class
, and :focus
, you can use <input type="radio">
, name
, and :checked
, with <label>
to help style them like buttons.
Note the adjacent sibling combinator +
, used to match <span>
only when it immediately follows a checked input.
.radio-button input {
display: none;
}
.radio-button span {
padding: 0.1em 0.6em;
background-color: rgb(239, 239, 239);
border: 2px outset rgb(118, 118, 118);
text-align: center;
}
.radio-button input[name="a"]:checked + span {
background-color: green;
}
.radio-button input[name="b"]:checked + span {
background-color: blue;
}
.radio-button input[name="c"]:checked + span {
background-color: red;
}
<label class="radio-button">
<input type="radio" name="a">
<span>a1</span>
</label>
<label class="radio-button">
<input type="radio" name="a">
<span>a2</span>
</label>
<label class="radio-button">
<input type="radio" name="b">
<span>b1</span>
</label>
<label class="radio-button">
<input type="radio" name="b">
<span>b2</span>
</label>
<label class="radio-button">
<input type="radio" name="b">
<span>b3</span>
</label>
<label class="radio-button">
<input type="radio" name="c">
<span>c1</span>
</label>
<label class="radio-button">
<input type="radio" name="c">
<span>c2</span>
</label>
Also see:
How to Style a Selected Radio Buttons Label?