How to Hide Only the Box in a Checkbox Using CSS
Showcase
Recently, in search or filtering settings, it’s common to indicate ON/OFF by changing only the background without showing the checkbox box. The R, G, B above are checkboxes implemented in that way.
Code
HTML
<input type="checkbox" id="box_R" hidden checked>
<label for="box_R" class="option">R</label>
<input type="checkbox" id="box_G" hidden checked>
<label for="box_G" class="option">G</label>
<input type="checkbox" id="box_B" hidden>
<label for="box_B" class="option">B</label>
hidden
: Hides the checkbox box. If you just remove the box there would be nowhere to click, so alabel
is used to create a clickable area.checked
: The checkbox starts in a selected state by default. Removing this attribute makes the checkbox start in an unchecked (off) state.
CSS
The following CSS is written directly with the HTML
code so you can easily test it. In practice it’s better to place this in a separate CSS file.
<style>
.option {
padding: 0 .4em 0 .4em;
border: 2px solid transparent;
border-radius: 5px;
}
input#box_R:checked + label {background-color: #aa0000; color: #ffffff;}
input#box_G:checked + label {background-color: #00aa00; color: #ffffff;}
input#box_B:checked + label {background-color: #0000aa; color: #ffffff;}
</style>
.option
: Simply a style to make the box look nice.intput#box_*:checked + label
: Means change the label’s style when the box is checked. When the checkbox is checked, it changes the background color and text color of the followinglabel
.