If you've always wondered how to create simple checkbox and radio style buttons on your website then our experienced front end developer, Tiberiu Raducea here at Reflect Digital is here to help.
Check out the key pointers on checkbox and radio style buttons below:
So how do you create simple checkbox and radio styles?
It's really important to wrap our custom input with a label element with our class "custom-checkbox" so that it gets focused every time a user clicks the text as well as following the input with a span that has our text. We'll find out why the order is important when we apply our styles.
Firstly, we style the label and input:
We need to hide our standard input but not completely so that it can still be focused by people not using a mouse. In order to do that we apply the following styling:
Secondly, we style the text and our new checkbox.
For that we need to add a pseudo-element ":before" inside the span that we added after the input. Learn more about pseudo-elements here
We want to position our new checkbox to the left and we do this by positioning the pseudo-element absolute. An absolute element is constrained by relative parents, therefore, we need to set the position relative for our label. Now that we have our positions set, we need to define the display property of our span and set a padding-left to avoid overlapping with our absolute positioned pseudo-element.
By now we should have something like this:
And lastly, we style the checked state of the new input styles. In which we will use a mix of new selectors to help us to achieve our goal.
Notice the “+” in our CSS selector. That targets the next span following our input. The order is really important in the mark-up. If we added the span before the input, our selector will not target anything as it would only be looking for a span after the input. We could also use “~” but that will target all spans following our input. It is of course separated by it’s parent so any span outside our input containing label will not be affected.
Now clicking the new checkbox or text should produce:
However you will find that the transition is not smooth, so we can now move one step further with our styles by applying smoothing to our transition.
We can do that by adding these css properties to our pseudo-element:
In our example, we are animating the background and font-size to create a smooth visual effect.
See the Pen
Simple custom checkbox styles by Reflect Dev (@reflectdigital) on CodePen.
https://codepen.io/reflectdigital/pen/WmoVoP
Follow us on Codepen for more Simple CSS tutorials
More advanced users can use SCSS: