Styling checkboxes using only css

Posted on: Feb 12, 2017 by admin

Styling a checkbox using css has been made possible with the invention of the css :checked pseudo class. You can't style an checkbox input element directly by using css.

In this article i am going to show a step by step proccess on how we can style a checkbox input element using only css.

 

1) We need an input type of checkbox and a label for this input.


    First thing to do is set myForm class to postition relative.

      <form class="myForm" action="#">           
            <input type="checkbox" name="myCheckBox" id="checkbox">
            <label for="checkbox">My checkbox</label>
      </form>

The for attribute of label must match the id attribute of input type checkbox, so when we click on the text of the label, the input is checked or unchecked.

2) Style the label:before pseudo class exactly as the design of the uncecked checkbox we want

label::before{
  width: 20px; 
  height: 20px; 
  border: 1px solid #2196F3;
  content: ' ';
  border-radius: 10px;
  float: left;
  margin:0 10px;
  cursor: pointer;
}


So in this example we will have a circle checkbox with a blue border as a unchecked checkbox element. You can find the styles of this example in the source code i will provide below. As i explained in the first step, if we click inside the label::before circle, our checkbox with get checked. 

3) Find out when our checkbox is checked and display a label::after pseudo class to make it look as an checked checkbox.

label::after{
  display: none;
  top: 6px;
  left: 16px;
  content: '';
  color: #2196F3;
  position: absolute;
  width: 10px;
  height: 10px;
  background-color: #2196F3;
  border-radius: 5px;
  cursor: pointer;
}

We style the label::after pseudo class, set it to position absolute so we can put it inside our label::before circle, so it will look as an checked checkbox. We set it to display none so it will be visible only when our checkbox element is checked. This can be checked by the folloing code:

input[type=checkbox]:checked + label::after{display: block;}

This line of code makes sure that the label::after will only be visible when our checkbox element is checked, and when it's unckecked make it unvisible.

 

4) Make our checkbox element invisible

The last step is to make our checkbox element unvisible for users.

input[type=checkbox]{display:none;}

This is the unstyled version of our checkbox so we dont want it to be visible to our users.

 

Conclusion

The most important thing is that "for" attribute of label must match the "id" attribute of input type checkbox. The label::before will behave as an unchecked checkbox and the label::after will make it look as an checked checkbox. Then we can hide our real checkbox because our styled label pseudo class will do the work.

Comments