How to style a checkbox using CSS
P粉252116587
2023-08-23 12:39:36
<p>I'm trying to style a checkbox using the following: </p>
<p><br /></p>
<pre class="brush:html;toolbar:false;"><input type="checkbox" style="border:2px dotted #00f;display:block;background:#ff0000;" />< /pre>
<p><br /></p>
<p>But the style was not applied. The checkbox still displays its default style. How to give it a specific style? </p>
By using the new functionality that comes with the
:after
and:before
pseudo-classes, you can achieve very cool custom checkbox effects. The advantage of this is that you don't need to add anything else to the DOM, just the standard checkbox.Please note that this only works on compatible browsers. I believe this has to do with some browsers not allowing you to set
:after
and:before
on input elements. Unfortunately, this means that currently only WebKit browsers are supported. Firefox Internet Explorer still allows checkboxes to function, just without styling, which is expected to change in the future (the code does not use the vendor prefix).This is just a WebKit browser solution (Chrome, Safari, mobile browsers)
View example Fiddle
Extra Webkit style flipped fiddle
renew:
The answers below refer to the situation before CSS 3 was widely used. In modern browsers, including Internet Explorer 9 and later, it's easier to create checkbox replacements with your favorite styles, without using JavaScript.
Here are some useful links:
It is worth noting that the fundamental problem has not changed. You still can't apply styles (borders, etc.) directly to the checkbox element and have those styles affect the display of the HTML checkbox. What has changed, however, is that it is now possible to hide the actual checkbox and replace it with your own style element, using just CSS. In particular, since CSS now has widely supported
:checked
selectors, you can make replacements correctly reflect the checked state of the box.Old Answer
This is a useful article on styling checkboxes. Basically, this author found that it varies hugely between browsers, and no matter how you style it, many browsers always show the default checkbox. So there really isn't an easy way.
It's not hard to imagine a workaround where you could use JavaScript to overlay an image on the checkbox, and then clicking on the image causes the real checkbox to be checked. Users without JavaScript will see the default checkbox.
Edited to add: Here is a nice script that does this for you ; it hides the real checkbox element, replaces it with a styled scope, and redirects the click event.