DEV Community

Muhammad Rauf
Muhammad Rauf

Posted on

How to Style a Checkbox using CSS

How to Style a Checkbox using CSSCSS checkbox is used to choose various options from a list of options at a time. Usually, the checkbox is square with a place inside the box. When the user clicks on the box place then it is said to use is selected. The checkbox is the most excellent option for when someone decides on more than one option from the given list of choices then this will be the most suitable option but in the case of a radio button, we can choose only one radio button at a time.

Example: Let suppose in an exercise, the specific question commonly has 4 options. In that more question if more than 2 options are correct. We can select them together. But If we take the usual radio button we can select only 1 option at a time but that is not the case. We have to select more than 2 options at a time so we need to used the checkbox to achieve our requirements.

Types of Checkboxes

1.Default checkboxes
2.Custom checkboxes

Default checkboxes

The default checkbox is not required to add any additional styles. CSS libraries by default provided with some styles for this checkbox.

<form action="cart.php">
<label>Have a bike?<br></label>
<input type="checkbox" name="bike">
<input type="submit" value="Submit">
</form>
Enter fullscreen mode Exit fullscreen mode

Custom Checkboxes

This Custom checkbox must require adding additional styles because these are user-required checkboxes so based on their requirement, they have to provide CSS styles.

<h1>Custom Checkboxes</h1>
<p>CSS Stands for?</p>
<label class="container">Cascading Style Sheet
  <input type="checkbox" checked="checked">
  <span class="checkmark"></span>
</label>
<style>
.container {
  display: block;
  position: relative;
  padding-left: 35px;
  margin-bottom: 12px;
  cursor: pointer;
  font-size: 22px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
.container input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}
.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 25px;
  width: 25px;
  background-color: #eee;
}
.container:hover input ~ .checkmark {
  background-color: hotpink;
}
.container input:checked ~ .checkmark {
  background-color: #2ef6F3;
}
.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}
.container input:checked ~ .checkmark:after {
  display: block;
}
.container .checkmark:after {
  left: 9px;
  top: 5px;
  width: 5px;
  height: 10px;
  border: solid white;
  border-width: 0 3px 3px 0;
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
}
</style>
Enter fullscreen mode Exit fullscreen mode

I have shared this post from How to style a checkbox using CSS
, You can read the details from there.

If you have any question please discuss below. Help to improve things for others. Thank you.

Top comments (0)