Skip to main content

Custom Checkbox

Wrong implementation​

Current code hides the standard <input type="checkbox"> element using display: none;, which makes it inaccessible for keyboard interaction because the element is effectively removed from the document flow.

HTML​

<input type="checkbox" class="customCheckbox" id="checkbox1" />
<label for="checkbox1" class="customLabel"></label>

CSS​

.customCheckbox {
display: none;
}

.customLabel {
cursor: pointer;
height: 25px;
width: 25px;
background-color: #eee;
display: inline-block;
border-radius: 5px;
position: relative;
box-sizing: border-box;
}

.customCheckbox:checked + .customLabel {
background-color: transparent;
}

.customCheckbox:checked + .customLabel::before {
content: "😊";
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
font-size: 20px;
}

Right implementation​

Use a technique that visually hides the checkbox while keeping it accessible for keyboard navigation and interaction. This can be done by using opacity: 0

HTML​

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Custom Checkbox</title>
<style>
.customCheckbox {
opacity: 0;
position: absolute;
z-index: -1;
}

.customLabel {
cursor: pointer;
height: 25px;
width: 25px;
background-color: #eee;
display: inline-block;
border-radius: 5px;
position: relative;
box-sizing: border-box;
}

.customCheckbox:checked + .customLabel {
background-color: transparent;
}

.customCheckbox:checked + .customLabel::before {
content: "😊";
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
font-size: 20px;
}
</style>
</head>
<body>
<input type="checkbox" class="customCheckbox" id="checkbox1" />
<label for="checkbox1" class="customLabel"></label>
</body>
</html>