The default checkbox supplied by most browsers is not that visually appealing. Although you can increase, or decrease the size, there is very little you can do with it in terms of styling.
So, what do you do should you wish to have something a little more stylish? Let me show you how to create a replacement checkbox to add flair to your mundane forms.
The answer is to create your own display. What we’ll do in this example is essentially link up a label to the checkbox, hide the checkbox so that we can use its functionality, and display a replacement using pseudo-elements. This will all be done in pure HTML and CSS.
Animated checkbox basics
The first thing we need to do is create our display, which is very basic.
Hide checkbox
Now we need to hide the actual checkbox. We still need it there because we still want to use its functionality. To hide the Checkbox, we add the following styling.
Adding in alt
So if there isn’t a checkbox, how can you tell what state everything is? Well, the answer is you create your own checkbox. The next part of the code will create a basic border for the new checkbox using the first pseudo-element while adding some style to the attached label.
Adding checked status
We’ll use the second pseudo-element for the actual checked status. This first code will display the checked status regardless of the checkboxes actual state. We’ll handle that in the second part.
Alternating states
The final part of the code allows us the toggle the checked pseudo element’s opacity to indicate the checked state. The two blocks of code are for both the checked and non-checked status.
Demo
See the Pen Checkbox replacement by Dean Pugh (@wezlar) on CodePen.
Conclusion
And that is everything you need. You can modify the :before
element of the label to be whatever size, shape and colour you require that can be created in CSS. The second :after
element can also be modified in the same way, allowing you to create whatever checked status you desire. You can even go beyond that with the animation between each status at your mercy.
Having the checkbox set up this way even makes it easier to create the same identical look between browsers. Something that is much harder to do if you use the browser-supplied version.