Styling checkboxes using only css

By Focusoncode May 13, 2018

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

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

how-to-style-checkboxes-using-css

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

The first thing to do is set a myForm class to position relative.


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

The attribute of the 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 unchecked checkbox we want

Before


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 an 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 getting checked.

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


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 a 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 following 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 unchecked make it invisible.

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 don’t want it to be visible to our users.

Conclusion

The most important thing is that “for” attribute of the 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 a checked checkbox. Then we can hide our real checkbox because our styled label pseudo class will do the work.

Leave a Comment

Your email address will not be published.