如何使用CSS设置复选框样式 [英] How to style a checkbox using CSS

查看:91
本文介绍了如何使用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:

  • Creating Custom Form Checkboxes with Just CSS
  • Easy CSS Checkbox Generator
  • Stuff You Can Do With The Checkbox Hack
  • Implementing Custom Checkboxes and Radio Buttons with CSS3
  • How to Style a Checkbox With 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.

这篇关于如何使用CSS设置复选框样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆