How to style a checkbox using CSS?

How to style a checkbox using CSS?

Hi,

You can use the appearance: none property and custom styles:

/* Hide the default checkbox */
input[type="checkbox"] {
  appearance: none;
  width: 20px;
  height: 20px;
  background: #eee;
  border: 2px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

/* Custom checkmark */
input[type="checkbox"]:checked {
  background: #4caf50;
  border-color: #4caf50;
  position: relative;
}

input[type="checkbox"]:checked::before {
  content: "\2714"; /* Unicode checkmark */
  position: absolute;
  top: 2px;
  left: 2px;
  color: white;
  font-size: 16px;
}

appearance: none; removes the default styling of the checkbox.

Custom width, height, background, border, and border-radius are applied.

When the checkbox is checked (:checked), it changes the background and border color.

The ::before pseudo-element is used to insert a Unicode checkmark (\2714) when the checkbox is checked.

Another approach other what Devan has mentioned is to use a custom image for the checkbox:

/* Hide the default checkbox */ input[type=“checkbox”] { opacity: 0; position: relative; width: 20px; height: 20px; cursor: pointer; }

/* Custom image for unchecked state */ input[type=“checkbox”]::before { content: ‘’; display: block; position: absolute; width: 20px; height: 20px; background: url(‘unchecked.png’) no-repeat center center; background-size: contain; }

/* Custom image for checked state */ input[type=“checkbox”]:checked::before { background: url(‘checked.png’) no-repeat center center; background-size: contain; }

The default checkbox is hidden by setting its opacity to 0.

The ::before pseudo-element is used to display a custom image for both the unchecked and checked states.

background: url(‘unchecked.png’) and background: url(‘checked.png’) set the respective images for the checkbox states.

You can even use ::after pseudo-element for custom styles:

/* Custom styles for the checkbox */
input[type="checkbox"] {
  position: absolute;
  opacity: 0;
  cursor: pointer;
}

/* Custom checkbox style */
input[type="checkbox"] + label {
  position: relative;
  padding-left: 30px;
  cursor: pointer;
}

/* Custom box */
input[type="checkbox"] + label::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 20px;
  height: 20px;
  border: 2px solid #ddd;
  background: #fff;
  border-radius: 4px;
}

/* Custom checkmark */
input[type="checkbox"]:checked + label::after {
  content: '';
  position: absolute;
  left: 5px;
  top: 5px;
  width: 10px;
  height: 10px;
  background: #4caf50;
  border-radius: 2px;
}
  • The default checkbox is hidden by setting its opacity to 0.
  • A label is used alongside the checkbox, and the label is styled to include padding for space.
  • The ::before pseudo-element of the label creates a custom box for the checkbox.
  • The ::after pseudo-element of the label creates a custom checkmark when the checkbox is checked.