As everyone knows, it is impossible to style input checkbox in CSS without any tricks. But there is a very easy workaround for that, of course, without JavaScript. To have custom styles for input checkbox you must create input checkbox with id attribute and label with for attribute (for must point on input’s ID). You need two images for your new styled checkbox. One image is for unchecked and second for checked state.
Table of Contents
CSS – custom styles (with image) for checkbox
I created in Inkscape in few seconds 2 images like below, and I placed them on one image (CSS sprite):
Then only you must do 2 easy CSS tricks. One is to place correctly above image as background (see on CSS rule for .checker
) and to use “+” is CSS selector for input and label. Remember that input checkbox must be just before label!
HTML:
<div>Check me!</div> <input id="trigger" type="checkbox"> <label for="trigger" class="checker"></label>
CSS:
#trigger { display: none; } .checker { background-image: url(assets/checkboxes.png); background-position: left center; background-size: auto 100%; width: 40px; height: 40px; background-repeat: no-repeat; } #trigger:checked + .checker { background-position: right center; }
Results:
When to use custom CSS styles for checkbox
The short answer is: it depends 🙂 In my honest opinion, we should not change in CSS the native look of input type checkbox. You can ask why? Because this is a native element which, nowadays, looks nice in all modern browsers. This is not time when input type checkbox was looking pure in Internet Explorer 10. So if you have a possibility to keep native styles of input type checkbox – stay with that.
But probably you are reading this article because you are sure you want to change CSS styles of checkbox. So it is advised to change it look and feel when you are developing a project with fully defined styles (let’s say that company branding requires that). So then there is no other way, you are than obligated to code that the same as designer did it. Also it would be good to provide a custom CSS styles for input checkbox when you want to do something uncommon. To have some unique (or even funny) picture on checked or unchecked input.