How to style a checkbox using CSS?
Checkbox is an HTML element which is used to take input from the user. Although it is bit complicated to style it but using Pseudo Elements like :before, :after, :hover and :checked, it is possible to style a checkbox. In order to style the checkbox the user first need to hide the default checkbox which can be done by setting the value of the visibility property to hidden.
Example 1: Consider the example where HTML checkbox is styled using CSS. First three check-boxes are created and then the default check-boxes are hide and new checkbox is created using height and width attribute. Set the height and width attribute to 25px and initial background color to black. The check-mark is also styled manually by using webkit. “:checked” is used to style checkbox after it is checked. When the user clicks the checkbox, the background color is set to green.
Basically you should approach by thinking about the scenarios in which you want your checkbox to be styled differently like when it is normal, active, hovered over or checked etc. Then for each scenario specify different styles as used in normal CSS. Moreover it can also be possible to change the check-mark.
- “~” is the sibling combinator which selects all the elements which are preceded by the former selector.
- “:hover” is used to style the checkbox when user hovers over it. Notice that when the mouse pointer move over the checkbox the color of it changes to yellow.
- “:active” is used to style the checkbox when it is active. Notice that when click the checkbox it will first notice a red color and then the green color.
Example 2: Consider another example with a bit modified design of check-mark.