如何使用 CSS 设置复选框的样式
我正在尝试使用以下方法设置复选框的样式:
I am trying to style a checkbox using the following:
<input type="checkbox" style="border:2px dotted #00f;display:block;background:#ff0000;" />
但是没有应用样式.该复选框仍显示其默认样式.如何给它指定样式?
But the style is not applied. The checkbox still displays its default style. How do I give it the specified style?
推荐答案
更新:
以下答案引用了 CSS 3 广泛使用之前的状态.在现代浏览器(包括 Internet Explorer 9 及更高版本)中,使用您喜欢的样式创建复选框替换更简单,而无需使用 JavaScript.
The below answer references the state of things before widespread availability of CSS 3. In modern browsers (including Internet Explorer 9 and later) it is more straightforward to create checkbox replacements with your preferred styling, without using JavaScript.
这里有一些有用的链接:
Here are some useful links:
- 只使用 CSS 创建自定义表单复选框李>
- 简单的 CSS 复选框生成器
- 使用 Checkbox Hack 可以做的事情
- 使用 CSS3 实现自定义复选框和单选按钮
- 如何使用 CSS 设置复选框的样式
值得注意的是,根本问题没有改变.您仍然不能将样式(边框等)直接应用于复选框元素,并且这些样式会影响 HTML 复选框的显示.然而,改变的是现在可以隐藏实际的复选框并用您自己的样式元素替换它,只使用 CSS.特别是,因为 CSS 现在有一个广泛支持的 :checked
选择器,您可以使您的替换正确反映框的选中状态.
It is worth noting that the fundamental issue 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's now possible to hide the actual checkbox and replace it with a styled element of your own, using nothing but CSS. In particular, because CSS now has a widely supported :checked
selector, you can make your replacement correctly reflect the checked status of the box.
老答案
这是一篇关于样式复选框的有用文章.基本上,该作者发现它因浏览器而异,而且许多浏览器总是显示默认复选框,无论您如何设置它.所以真的没有一个简单的方法.
Here's a useful article about styling checkboxes. Basically, that writer found that it varies tremendously from browser to browser, and that many browsers always display the default checkbox no matter how you style it. So there really isn't an easy way.
不难想象一种解决方法,您可以使用 JavaScript 在复选框上叠加图像,然后单击该图像会导致真正的复选框被选中.没有 JavaScript 的用户会看到默认复选框.
It's not hard to imagine a workaround where you would use JavaScript to overlay an image on the checkbox and have clicks on that image cause the real checkbox to be checked. Users without JavaScript would see the default checkbox.
编辑添加:这里是 一个很好的脚本可以为你做这件事;它隐藏了真正的复选框元素,将其替换为样式跨度,并重定向点击事件.
Edited to add: here's a nice script that does this for you; it hides the real checkbox element, replaces it with a styled span, and redirects the click events.
相关文章