Custom Checkbox Tutorial in HTML

In html how to create a custom checkbox using pure CSS that is entirely responsive and accessible. I will go over my planning and thought process for creating this checkbox as well as explain why I use each CSS style. By the end of this video you will have a basic understanding of how CSS checkbox selectors work as well as how to support screen reader accessibility

background_styles.css

@import url('https://fonts.googleapis.com/css?family=Raleway');

* {
    font-family: Raleway;
}

html {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #DFDFDF;
}

Table of Contents

index.html

<!DOCTYPE html>
<html>
    <head>
      <link rel="stylesheet" href="background_styles.css">
      <link rel="stylesheet" href="styles.css">
      <title>Custom Checkbox</title>
    </head>
    <body>
      <div class="checkbox-container">
        <input type="checkbox" id="cb1" disabled checked>
        <label for="cb1">Checkbox 1</label>
      </div>
      <br>
      <div class="checkbox-container">
        <input type="checkbox" id="cb2" disabled>
        <label for="cb2">Checkbox 2</label>
      </div>
      <br>
      <div class="checkbox-container">
        <input type="checkbox" id="cb3">
        <label for="cb3">Checkbox 3</label>
      </div>
    </body>
</html>

styles.css

* {
    box-sizing: border-box;
}

.checkbox-container {
    display: flex;
    align-items: center;
}

.checkbox-container label {
    cursor: pointer;
    display: flex;
}

.checkbox-container input[type='checkbox'] {
    cursor: pointer;
    opacity: 0;
    position: absolute;
}

.checkbox-container label::before {
    content: '';
    width: 1em;
    height: 1em;
    border-radius: .15em;
    margin-right: .5em;
    border: .05em solid black;
}

.checkbox-container label:hover::before,
.checkbox-container input[type='checkbox']:hover + label::before {
    background-color: #35E07D;
}

.checkbox-container input[type='checkbox']:focus + label::before {
    box-shadow: 0 0 20px black;
}

.checkbox-container input[type='checkbox']:disabled + label,
.checkbox-container input[type='checkbox']:disabled {
    color: #aaa;
    cursor: default;
}

.checkbox-container input[type='checkbox']:checked + label::before {
    content: '\002714';
    background-color: #27AE60;
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
}

.checkbox-container input[type='checkbox']:disabled + label::before {
    background-color: #ccc;
    border-color: #999;
}

Leave a Comment