DEV Community

Cover image for How to style a checkbox using CSS
JetThoughts Dev for JetThoughts

Posted on • Edited on • Originally published at jetthoughts.com

How to style a checkbox using CSS

In this post I’l show you exactly how to make awesome checkboxes with just CSS.

<div>
  <input id="first_name" type="checkbox" checked="checked">
  <label for="first_name">First Name</label>
</div>
Enter fullscreen mode Exit fullscreen mode

Let’s take a few simple steps:

  • Hide the browser’s default checkbox.
  • Create a custom checkbox. We will use a pseudo-element :before for the substrate.
  • On mouse-over, add a darkly on 10% background color.
  • Style the checkmark/indicator, by pseudo-element :after
  • Show or hide the checkmark when checked.

Hide the browser’s default checkbox

input {
  position: absolute;
  opacity: 0;
  height: 0;
  width: 0;
}
Enter fullscreen mode Exit fullscreen mode

Create a custom checkbox

label {
  position: relative;
  display: block;
  padding-left: 30px;
  cursor: pointer;
}
label:before {
  content: '';
  position: absolute;
  top: 50%;
  margin-top: -10px;
  left: 0;
  display: block;
  height: 20px;
  width: 20px;
  background-color: #50CDBE;
  border-radius: 3px;
}
Enter fullscreen mode Exit fullscreen mode

On mouse-over, add a darkly on 10% background color

label:hover:before {
  background-color: #1AE6E6;
}
Enter fullscreen mode Exit fullscreen mode

Style the checkmark/indicator

label:after {
  content: '';
  position: absolute;
  left: 7px;
  top: 1px;
  width: 5px;
  height: 10px;
  border: solid #333;
  border-width: 0 3px 3px 0;
  transform: rotate(45deg);
  opacity: 0;
}
Enter fullscreen mode Exit fullscreen mode

Show or hide the checkmark when checked

input:checked + label:after {
  opacity: 1;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)