【问题标题】:How to style a checkbox using CSS如何使用 CSS 设置复选框的样式
【发布时间】:2010-11-10 19:57:01
【问题描述】:

我正在尝试使用以下方法设置复选框的样式:

<input type="checkbox" style="border:2px dotted #00f;display:block;background:#ff0000;" />

但是没有应用样式。该复选框仍显示其默认样式。如何给它指定样式?

【问题讨论】:

  • wrote a tutorial 关于如何仅使用 CSS 自定义复选框和单选,以及创建开/关开关。看看吧!
  • 无论您通过 CSS 对复选框或单选按钮的样式做出何种决定,请确保它们可访问。截至此评论,我相信到目前为止 33 个答案中只有 2 个是可访问的。对于其余的答案,如果不是所有的可访问性,您将切断最多。 (ctrl+f“可访问性”)
  • 现在有一个原生 CSS 属性,跳到this answer

标签: html css checkbox


【解决方案1】:

更新:

以下答案引用了 CSS 3 广泛使用之前的状态。在现代浏览器(包括 Internet Explorer 9 及更高版本)中,使用您喜欢的样式创建复选框替换更简单,而无需使用 JavaScript。

这里有一些有用的链接:

值得注意的是,根本问题没有改变。您仍然不能将样式(边框等)直接应用于复选框元素,并让这些样式影响 HTML 复选框的显示。然而,改变的是现在可以隐藏实际的复选框并用您自己的样式元素替换它,只使用 CSS。特别是,因为 CSS 现在有一个广泛支持的 :checked 选择器,您可以使您的替换正确地反映框的选中状态。


老答案

这里是a useful article about styling checkboxes。基本上,该作者发现它因浏览器而异,而且许多浏览器总是显示默认复选框,无论您如何设置它。所以真的没有一个简单的方法。

不难想象一种解决方法,您可以使用 JavaScript 在复选框上叠加图像,然后单击该图像会导致真正的复选框被选中。没有 JavaScript 的用户会看到默认复选框。

编辑添加:这里是a nice script that does this for you;它隐藏了真正的复选框元素,将其替换为样式跨度,并重定向点击事件。

【讨论】:

  • 这个答案已经过时了!主链接指向一个比较 IE6 和 IE7 样式的网站...
  • 公平点——在现代浏览器中,基本点不再是真的了。我已经更新了一些较新的链接,但将原始链接保留为旧浏览器的资源。
  • Easy CSS Checkbox Generator,非常简单且友好。还带有用于自定义创建的 GUI!非常感谢。 :)
  • 我对旧答案很感兴趣,因为我希望此功能与 IE8+ 和其他浏览器(chrome、firefox 和 safari)兼容。但是我找不到关于你推荐的插件的太多反馈ryanfait.com/resources/custom-checkboxes-and-radio-buttons
  • 这不是一个很有用的答案——它只是一个文章列表,其中大部分现在已经很老了。
【解决方案2】:

您可以使用:after:before 伪类附带的新功能来实现非常酷的自定义复选框效果。这样做的好处是:您不需要向 DOM 添加任何其他内容,只需添加标准复选框即可。

请注意,这仅适用于兼容的浏览器。我相信这与某些浏览器不允许您在输入元素上设置:after:before 的事实有关。不幸的是,这意味着目前仅支持 WebKit 浏览器。 Firefox + Internet Explorer 仍将允许复选框起作用,只是未设置样式,这有望在未来发生变化(代码不使用供应商前缀)。

这只是一个 WebKit 浏览器解决方案(Chrome、Safari、移动浏览器)

See Example Fiddle

$(function() {
  $('input').change(function() {
    $('div').html(Math.random());
  });
});
/* Main Classes */
.myinput[type="checkbox"]:before {
  position: relative;
  display: block;
  width: 11px;
  height: 11px;
  border: 1px solid #808080;
  content: "";
  background: #FFF;
}

.myinput[type="checkbox"]:after {
  position: relative;
  display: block;
  left: 2px;
  top: -11px;
  width: 7px;
  height: 7px;
  border-width: 1px;
  border-style: solid;
  border-color: #B3B3B3 #dcddde #dcddde #B3B3B3;
  content: "";
  background-image: linear-gradient(135deg, #B1B6BE 0%, #FFF 100%);
  background-repeat: no-repeat;
  background-position: center;
}

.myinput[type="checkbox"]:checked:after {
  background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAQAAABuW59YAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAB2SURBVHjaAGkAlv8A3QDyAP0A/QD+Dam3W+kCAAD8APYAAgTVZaZCGwwA5wr0AvcA+Dh+7UX/x24AqK3Wg/8nt6w4/5q71wAAVP9g/7rTXf9n/+9N+AAAtpJa/zf/S//DhP8H/wAA4gzWj2P4lsf0JP0A/wADAHB0Ngka6UmKAAAAAElFTkSuQmCC'), linear-gradient(135deg, #B1B6BE 0%, #FFF 100%);
}

.myinput[type="checkbox"]:disabled:after {
  -webkit-filter: opacity(0.4);
}

.myinput[type="checkbox"]:not(:disabled):checked:hover:after {
  background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAQAAABuW59YAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAB2SURBVHjaAGkAlv8A3QDyAP0A/QD+Dam3W+kCAAD8APYAAgTVZaZCGwwA5wr0AvcA+Dh+7UX/x24AqK3Wg/8nt6w4/5q71wAAVP9g/7rTXf9n/+9N+AAAtpJa/zf/S//DhP8H/wAA4gzWj2P4lsf0JP0A/wADAHB0Ngka6UmKAAAAAElFTkSuQmCC'), linear-gradient(135deg, #8BB0C2 0%, #FFF 100%);
}

.myinput[type="checkbox"]:not(:disabled):hover:after {
  background-image: linear-gradient(135deg, #8BB0C2 0%, #FFF 100%);
  border-color: #85A9BB #92C2DA #92C2DA #85A9BB;
}

.myinput[type="checkbox"]:not(:disabled):hover:before {
  border-color: #3D7591;
}

/* Large checkboxes */
.myinput.large {
  height: 22px;
  width: 22px;
}

.myinput.large[type="checkbox"]:before {
  width: 20px;
  height: 20px;
}

.myinput.large[type="checkbox"]:after {
  top: -20px;
  width: 16px;
  height: 16px;
}

/* Custom checkbox */
.myinput.large.custom[type="checkbox"]:checked:after {
  background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGHRFWHRBdXRob3IAbWluZWNyYWZ0aW5mby5jb23fZidLAAAAk0lEQVQ4y2P4//8/AyUYwcAD+OzN/oMwshjRBoA0Gr8+DcbIhhBlAEyz+qZZ/7WPryHNAGTNMOxpJvo/w0/uP0kGgGwGaZbrKgfTGnLc/0nyAgiDbEY2BCRGdCDCnA2yGeYVog0Aae5MV4c7Gzk6CRqAbDM2w/EaQEgzXgPQnU2SAcTYjNMAYm3GaQCxNuM0gFwMAPUKd8XyBVDcAAAAAElFTkSuQmCC'), linear-gradient(135deg, #B1B6BE 0%, #FFF 100%);
}

.myinput.large.custom[type="checkbox"]:not(:disabled):checked:hover:after {
  background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGHRFWHRBdXRob3IAbWluZWNyYWZ0aW5mby5jb23fZidLAAAAk0lEQVQ4y2P4//8/AyUYwcAD+OzN/oMwshjRBoA0Gr8+DcbIhhBlAEyz+qZZ/7WPryHNAGTNMOxpJvo/w0/uP0kGgGwGaZbrKgfTGnLc/0nyAgiDbEY2BCRGdCDCnA2yGeYVog0Aae5MV4c7Gzk6CRqAbDM2w/EaQEgzXgPQnU2SAcTYjNMAYm3GaQCxNuM0gFwMAPUKd8XyBVDcAAAAAElFTkSuQmCC'), linear-gradient(135deg, #8BB0C2 0%, #FFF 100%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table style="width:100%">
  <tr>
    <td>Normal:</td>
    <td><input type="checkbox" /></td>
    <td><input type="checkbox" checked="checked" /></td>
    <td><input type="checkbox" disabled="disabled" /></td>
    <td><input type="checkbox" disabled="disabled" checked="checked" /></td>
  </tr>
  <tr>
    <td>Small:</td>
    <td><input type="checkbox" class="myinput" /></td>
    <td><input type="checkbox" checked="checked" class="myinput" /></td>
    <td><input type="checkbox" disabled="disabled" class="myinput" /></td>
    <td><input type="checkbox" disabled="disabled" checked="checked" class="myinput" /></td>
  </tr>
  <tr>
    <td>Large:</td>
    <td><input type="checkbox" class="myinput large" /></td>
    <td><input type="checkbox" checked="checked" class="myinput large" /></td>
    <td><input type="checkbox" disabled="disabled" class="myinput large" /></td>
    <td><input type="checkbox" disabled="disabled" checked="checked" class="myinput large" /></td>
  </tr>
  <tr>
    <td>Custom icon:</td>
    <td><input type="checkbox" class="myinput large custom" /></td>
    <td><input type="checkbox" checked="checked" class="myinput large custom" /></td>
    <td><input type="checkbox" disabled="disabled" class="myinput large custom" /></td>
    <td><input type="checkbox" disabled="disabled" checked="checked" class="myinput large custom" /></td>
  </tr>
</table>

Bonus Webkit style flipswitch fiddle

$(function() {
  var f = function() {
    $(this).next().text($(this).is(':checked') ? ':checked' : ':not(:checked)');
  };
  $('input').change(f).trigger('change');
});
body {
  font-family: arial;
}

.flipswitch {
  position: relative;
  background: white;
  width: 120px;
  height: 40px;
  -webkit-appearance: initial;
  border-radius: 3px;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  outline: none;
  font-size: 14px;
  font-family: Trebuchet, Arial, sans-serif;
  font-weight: bold;
  cursor: pointer;
  border: 1px solid #ddd;
}

.flipswitch:after {
  position: absolute;
  top: 5%;
  display: block;
  line-height: 32px;
  width: 45%;
  height: 90%;
  background: #fff;
  box-sizing: border-box;
  text-align: center;
  transition: all 0.3s ease-in 0s;
  color: black;
  border: #888 1px solid;
  border-radius: 3px;
}

.flipswitch:after {
  left: 2%;
  content: "OFF";
}

.flipswitch:checked:after {
  left: 53%;
  content: "ON";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<h2>Webkit friendly mobile-style checkbox/flipswitch</h2>
<input type="checkbox" class="flipswitch" /> &nbsp;
<span></span>
<br>
<input type="checkbox" checked="checked" class="flipswitch" /> &nbsp;
<span></span>

【讨论】:

  • Firefox 33.1/Linux:小提琴只显示默认复选框。看起来没什么不同。
  • @robsch 这在原始帖子中已明确指出。火狐或操作系统的版本无关紧要,它在火狐中不起作用。 “FF + IE 仍然允许复选框起作用,只是没有样式......”
  • 一个好方法。但并非所有浏览器都做得很好。据我检查,只有 Chrome 的输出最好。
  • 非常好。但是...这又是一种 IE 5.x 方法。仅限 Webkit。因为它并不总是遵守规则……这就是 webkit 浏览器的全部问题。
  • Win 上的 Firefox 58 和 IE11 也有默认复选框。
【解决方案3】:

开始之前(截至 2015 年 1 月)

最初的问题和答案现在大约有 5 年的历史了。因此,这是一个小小的更新。

首先,在样式复选框方面有多种方法。基本原则是:

  1. 您需要隐藏由浏览器设置样式的默认复选框控件,并且不能使用 CSS 以任何有意义的方式覆盖。

  2. 隐藏控件后,您仍然需要能够检测并切换其选中状态。

  3. 复选框的选中状态需要通过设置新元素的样式来反映。

解决方案(原则上)

以上可以通过多种方式实现——你经常会听到使用 CSS3 伪元素是正确的方法。实际上,没有真正的正确或错误的方法,这取决于最适合您将使用它的上下文的方法。也就是说,我有一个首选的方法。

  1. 将您的复选框包装在 label 元素中。这意味着即使它被隐藏,您仍然可以通过单击标签内的任意位置来切换其选中状态。

  2. 隐藏您的复选框。

  3. 添加一个新元素您将相应样式的复选框。它必须出现在复选框之后,以便可以使用 CSS 选择它并根据:checked 状态设置样式。 CSS 无法选择“向后”。

解决方案(在代码中)

label input {
  visibility: hidden;/* <-- Hide the default checkbox. The rest is to hide and allow tabbing, which display:none prevents */
  display: block;
  height: 0;
  width: 0;
  position: absolute;
  overflow: hidden;
}
label span {/* <-- Style the artificial checkbox */
  height: 10px;
  width: 10px;
  border: 1px solid grey;
  display: inline-block;
}
[type=checkbox]:checked + span {/* <-- Style its checked state */
  background: black;
}
<label>
  <input type='checkbox'>
  <span></span>
  Checkbox label text
</label>

细化(使用图标)

“但是,嘿!”我听到你喊。如果我想在框中显示一个漂亮的小勾号或十字怎么办?而且我不想使用背景图片!

嗯,这就是 CSS3 的伪元素可以发挥作用的地方。这些支持content 属性,它允许您注入代表任一状态的Unicode icons。或者,您可以使用第三方字体图标源,例如 font awesome(但请确保您还设置了相关的font-family,例如设置为FontAwesome

label input {
  display: none; /* Hide the default checkbox */
}

/* Style the artificial checkbox */
label span {
  height: 10px;
  width: 10px;
  border: 1px solid grey;
  display: inline-block;
  position: relative;
}

/* Style its checked state...with a ticked icon */
[type=checkbox]:checked + span:before {
  content: '\2714';
  position: absolute;
  top: -5px;
  left: 0;
}
<label>
  <input type='checkbox'>
  <span></span>
  Checkbox label text
</label>

【讨论】:

  • 不测:简体HTML、简体CSS、详解。
  • @AnthonyHayward - 更新的答案,这是由于使用 display:none 不会以可选项卡的方式实例化控件,我已经改变了
  • 我一直在努力寻找一个示例,其中复选框位于标签内部而不是之前/之后。这是一个非常有据可查和解释的解决方案。很高兴看到这个答案在 2016 年 1 月更新。
  • 仍然不能使用display: none 进行标签。
  • 如果您仍然遇到标签问题,请将 visibility: hidden; 替换为 opacity: 0 !important;
【解决方案4】:

有一种方法可以只使用 CSS。我们可以(ab)使用label 元素并设置该元素的样式。需要注意的是,这不适用于 Internet Explorer 8 及更低版本。

.myCheckbox input {
  position: relative;
  z-index: -9999;
}

.myCheckbox span {
  width: 20px;
  height: 20px;
  display: block;
  background: url("link_to_image");
}

.myCheckbox input:checked + span {
  background: url("link_to_another_image");
}
<label for="test">Label for my styled "checkbox"</label>
<label class="myCheckbox">
  <input type="checkbox" name="test" />
  <span></span>
</label>

【讨论】:

  • @GandalfStormCrow 这将适用于任何支持 :checked 伪类的浏览器,IE8 不支持该伪类。您可以检查这是否适用于 selectivizr.com - 它增加了对 :checked 和朋友的支持。
  • 也就是说IE9及以后的版本支持:checked。
  • IE8及以下有一个polyfill:github.com/rdebeasi/checked-polyfill
  • 它工作正常,但第一次闪烁。为什么会这样?
  • 我相信 hidden inputs 永远不会占据键盘焦点,所以这些是键盘无法访问的。
【解决方案5】:

我总是使用伪元素:before:after 来更改复选框和单选按钮的外观。它就像一个魅力。

更多信息请参考link

CODEPEN

步骤

  1. 使用 visibility:hiddenopacity:0position:absolute;left:-9999px 等 css 规则隐藏默认复选框。
  2. 使用:before 元素创建一个假复选框,并传递一个空白或不间断空格'\00a0'
  3. 当checkbox处于:checked状态时,传入unicodecontent: "\2713",即勾选;
  4. 添加:focus 样式以使复选框可访问。
  5. 完成

这是我的做法。

.box {
  background: #666666;
  color: #ffffff;
  width: 250px;
  padding: 10px;
  margin: 1em auto;
}
p {
  margin: 1.5em 0;
  padding: 0;
}
input[type="checkbox"] {
  visibility: hidden;
}
label {
  cursor: pointer;
}
input[type="checkbox"] + label:before {
  border: 1px solid #333;
  content: "\00a0";
  display: inline-block;
  font: 16px/1em sans-serif;
  height: 16px;
  margin: 0 .25em 0 0;
  padding: 0;
  vertical-align: top;
  width: 16px;
}
input[type="checkbox"]:checked + label:before {
  background: #fff;
  color: #333;
  content: "\2713";
  text-align: center;
}
input[type="checkbox"]:checked + label:after {
  font-weight: bold;
}

input[type="checkbox"]:focus + label::before {
    outline: rgb(59, 153, 252) auto 5px;
}
<div class="content">
  <div class="box">
    <p>
      <input type="checkbox" id="c1" name="cb">
      <label for="c1">Option 01</label>
    </p>
    <p>
      <input type="checkbox" id="c2" name="cb">
      <label for="c2">Option 02</label>
    </p>
    <p>
      <input type="checkbox" id="c3" name="cb">
      <label for="c3">Option 03</label>
    </p>
  </div>
</div>

使用:before:after 更加时尚

body{
  font-family: sans-serif;  
}

.container {
    margin-top: 50px;
    margin-left: 20px;
    margin-right: 20px;
}
.checkbox {
    width: 100%;
    margin: 15px auto;
    position: relative;
    display: block;
}

.checkbox input[type="checkbox"] {
    width: auto;
    opacity: 0.00000001;
    position: absolute;
    left: 0;
    margin-left: -20px;
}
.checkbox label {
    position: relative;
}
.checkbox label:before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    margin: 4px;
    width: 22px;
    height: 22px;
    transition: transform 0.28s ease;
    border-radius: 3px;
    border: 2px solid #7bbe72;
}
.checkbox label:after {
  content: '';
    display: block;
    width: 10px;
    height: 5px;
    border-bottom: 2px solid #7bbe72;
    border-left: 2px solid #7bbe72;
    -webkit-transform: rotate(-45deg) scale(0);
    transform: rotate(-45deg) scale(0);
    transition: transform ease 0.25s;
    will-change: transform;
    position: absolute;
    top: 12px;
    left: 10px;
}
.checkbox input[type="checkbox"]:checked ~ label::before {
    color: #7bbe72;
}

.checkbox input[type="checkbox"]:checked ~ label::after {
    -webkit-transform: rotate(-45deg) scale(1);
    transform: rotate(-45deg) scale(1);
}

.checkbox label {
    min-height: 34px;
    display: block;
    padding-left: 40px;
    margin-bottom: 0;
    font-weight: normal;
    cursor: pointer;
    vertical-align: sub;
}
.checkbox label span {
    position: absolute;
    top: 50%;
    -webkit-transform: translateY(-50%);
    transform: translateY(-50%);
}
.checkbox input[type="checkbox"]:focus + label::before {
    outline: 0;
}
<div class="container"> 
  <div class="checkbox">
     <input type="checkbox" id="checkbox" name="" value="">
     <label for="checkbox"><span>Checkbox</span></label>
  </div>

  <div class="checkbox">
     <input type="checkbox" id="checkbox2" name="" value="">
     <label for="checkbox2"><span>Checkbox</span></label>
  </div>
</div>

【讨论】:

    【解决方案6】:

    我会听从SW4's answer的建议。不再是:Volomike's answer 远远优于这里的所有答案(请注意我在对答案的评论中建议的改进)。如果您对替代方法感到好奇,请继续阅读此答案。


    首先,隐藏复选框并用自定义跨度覆盖它,建议使用此 HTML:

    <label>
      <input type="checkbox">
      <span>send newsletter</span>
    </label>
    

    标签中的换行巧妙地允许单击文本而无需“for-id”属性链接。然而,

    不要使用visibility: hiddendisplay: none 隐藏它

    它通过单​​击或点击来工作,但这是使用复选框的一种蹩脚的方式。有些人仍然使用更有效的 Tab 来移动焦点,Space 来激活,使用该方法隐藏会禁用它。如果表单很长,则将节省某人的手腕以使用tabindexaccesskey 属性。如果您观察系统复选框的行为,悬停时会有一个不错的阴影。样式良好的复选框应遵循此行为。

    cobberboy's answer 推荐Font Awesome,它通常比位图更好,因为字体是可缩放的矢量。使用上面的 HTML,我建议使用以下 CSS 规则:

    1. 隐藏复选框

       input[type="checkbox"] {
         position: absolute;
         opacity: 0;
         z-index: -1;
       }
      

      我只使用了否定的z-index,因为我的示例使用了足够大的复选框皮肤来完全覆盖它。我不推荐left: -999px,因为它不能在每个布局中重复使用。 Bushan wagh's answer 提供了一种防弹的方式来隐藏它并说服浏览器使用 tabindex,因此它是一个不错的选择。无论如何,两者都只是一个黑客。今天正确的做法是appearance: none,见Joost's answer

       input[type="checkbox"] {
         appearance: none;
         -webkit-appearance: none;
         -moz-appearance: none;
       }
      
    2. 样式复选框标签

       input[type="checkbox"] + span {
         font: 16pt sans-serif;
         color: #000;
       }
      
    3. 添加复选框皮肤

       input[type="checkbox"] + span:before {
         font: 16pt FontAwesome;
         content: '\00f096';
         display: inline-block;
         width: 16pt;
         padding: 2px 0 0 3px;
         margin-right: 0.5em;
       }
      

    \00f096 是 Font Awesome 的 square-o,调整填充以在焦点上提供均匀的虚线轮廓(见下文)。

    1. 添加复选框选中皮肤

       input[type="checkbox"]:checked + span:before {
         content: '\00f046';
       }
      

    \00f046是Font Awesome的check-square-o,和square-o的宽度不一样,这也是上面宽度样式的原因。

    1. 添加焦点轮廓

       input[type="checkbox"]:focus + span:before {
         outline: 1px dotted #aaa;
       }
      

      Safari 不提供此功能(请参阅 @Jason Sankey 的评论),请参阅 this answer 了解 Safari-only CSS

    2. 为禁用的复选框设置灰色

       input[type="checkbox"]:disabled + span {
         color: #999;
       }
      
    3. 在未禁用的复选框上设置悬停阴影

       input[type="checkbox"]:not(:disabled) + span:hover:before {
         text-shadow: 0 1px 2px #77F;
       }
      

    JS Fiddle 上测试它

    尝试将鼠标悬停在复选框上并使用 TabShift+Tab 移动和 Space切换。

    【讨论】:

    • 支持关注焦点问题:像这样的自定义不应该删除基本功能。请注意,尽管 Safari 不会将键盘焦点赋予复选框(甚至是默认复选框),但在实施包含焦点处理的解决方案时,这让我暂时感到困惑。
    • ìt 似乎 sn-p 中的复选框不再起作用?在 chrome windows 10 上
    • 不错的答案。为我的解决方案提供了基础——我在输入后使用了现有标签,您使用了额外的跨度,我得到了 Edge 和 FF 支持。
    • 这些答案中的大多数都忽略了可访问性。我喜欢这个答案保持原样。
    • @maxshuty 我也喜欢你的方法:当有人创建一个库时,通常只是承认他不能用他选择的母语编写简单的代码。恕我直言,FontAwesome 搞砸了他们使用 javascript 加载字体的免费计划,但我仍然喜欢它们,因为它们保持开源和免费许可证。我通常会在特定项目中使用我需要的免费图标的字体锻造子集(通常最大 5kB)。如果他们为我节省了精力,我很乐意支付,但不是他们在 Pro 计划中建议的每年 99 美元的疯狂费用。
    【解决方案7】:

    2022 可访问解决方案 - 使用accent-color

    2022 年更新: 请参阅this answer... 取决于您需要支持的浏览器以及您需要的自定义数量,您可能只想使用新的accent-color 属性并确保满足适当的contrast ratio 3:1 到确保accessibility。它也适用于radio 按钮:

    .red-input {
        accent-color: #9d3039;
        height: 30px; /* not needed */
        width: 30px; /* not needed */
    }
    <input class="red-input" type="checkbox" />
    
    <!-- Radio button example -->
    <input class="red-input" type="radio" />

    但是,如果您需要更多自定义,请继续...

    旧答案:

    我一直在滚动和滚动,这些答案只是以不止一种方式将可访问性扔到门外,violate WCAG。我添加了单选按钮,因为大多数时候当您使用自定义复选框时,您也需要自定义单选按钮。

    小提琴

    聚会迟到了,但不知何故这在 20192020、2021 年仍然很困难,所以我添加了三个可访问的解决方案并且容易加入。

    这些都是免费的JavaScript可访问免费的外部库*...

    如果您想即插即用,只需从小提琴中复制样式表,编辑 CSS 中的颜色代码以满足您的需求,然后就可以使用了。如果需要复选框,您可以添加自定义 svg 复选标记图标。我为那些非 CSS 的人添加了很多 cmets。

    如果您有长文本或小容器,并且遇到复选框或单选按钮输入下方的文本换行,则只需转换为 div like this

    更长的解释: 我需要一个不违反 WCAG、不依赖 JavaScript 或外部库、不破坏键盘导航(如制表键或空格键选择)、允许焦点事件的解决方案、一个允许同时选中的禁用复选框的解决方案并且未选中,最后是一个解决方案,我可以自定义复选框的外观,但是我想要不同的background-colorborder-radiussvg 背景等。

    我使用了来自@Jan Turoň 的this answer 的一些组合来提出我自己的解决方案,它似乎工作得很好。我已经完成了一个单选按钮小提琴,它使用了复选框中的许多相同代码,以便也可以使用单选按钮。

    我仍在学习可访问性,所以如果我遗漏了什么,请发表评论,我会尽力更正。

    这是我的复选框的代码示例:

    input[type="checkbox"] {
      position: absolute;
      opacity: 0;
      z-index: -1;
    }
    
    /* Text color for the label */
    input[type="checkbox"]+span {
      cursor: pointer;
      font: 16px sans-serif;
      color: black;
    }
    
    /* Checkbox un-checked style */
    input[type="checkbox"]+span:before {
      content: '';
      border: 1px solid grey;
      border-radius: 3px;
      display: inline-block;
      width: 16px;
      height: 16px;
      margin-right: 0.5em;
      margin-top: 0.5em;
      vertical-align: -2px;
    }
    
    /* Checked checkbox style (in this case the background is green #e7ffba, change this to change the color) */
    input[type="checkbox"]:checked+span:before {
      /* NOTE: Replace the url with a path to an SVG of a checkmark to get a checkmark icon */
      background-image: url('https://cdnjs.cloudflare.com/ajax/libs/ionicons/4.5.6/collection/build/ionicons/svg/ios-checkmark.svg');
      background-repeat: no-repeat;
      background-position: center;
      /* The size of the checkmark icon, you may/may not need this */
      background-size: 25px;
      border-radius: 2px;
      background-color: #e7ffba;
      color: white;
    }
    
    /* Adding a dotted border around the active tabbed-into checkbox */
    input[type="checkbox"]:focus+span:before,
    input[type="checkbox"]:not(:disabled)+span:hover:before {
      /* Visible in the full-color space */
      box-shadow: 0px 0px 0px 2px rgba(0, 150, 255, 1);
    
      /* Visible in Windows high-contrast themes
         box-shadow will be hidden in these modes and
         transparency will not be hidden in high-contrast
         thus box-shadow will not show but the outline will
         providing accessibility */
      outline-color: transparent; /*switch to transparent*/
      outline-width: 2px;
      outline-style: dotted;
      }
    
    
    /* Disabled checkbox styles */
    input[type="checkbox"]:disabled+span {
      cursor: default;
      color: black;
      opacity: 0.5;
    }
    
    /* Styles specific to this fiddle that you do not need */
    body {
      padding: 1em;
    }
    h1 {
      font-size: 18px;
    }
    <h1>
      NOTE: Replace the url for the background-image in CSS with a path to an SVG in your solution or CDN. This one was found from a quick google search for a checkmark icon cdn
    </h1>
    
    <p>You can easily change the background color, checkbox symbol, border-radius, etc.</p>
    
    <label>
      <input type="checkbox">
      <span>Try using tab and space</span>
    </label>
    
    <br>
    
    <label>
      <input type="checkbox" checked disabled>
      <span>Disabled Checked Checkbox</span>
    </label>
    
    <br>
    
    <label>
      <input type="checkbox" disabled>
      <span>Disabled Checkbox</span>
    </label>
    <br>
    
    <label>
      <input type="checkbox">
      <span>Normal Checkbox</span>
    </label>
    
    <br>
    
    <label>
      <input type="checkbox">
      <span>Another Normal Checkbox</span>
    </label>

    【讨论】:

      【解决方案8】:

      使用纯 CSS,:before:after 没什么好看的,没有变换,您可以关闭默认外观,然后使用内联背景图像对其进行样式设置,如下例所示。这适用于 Chrome、Firefox、Safari 和现在的 Edge (Chromium Edge)。

      INPUT[type=checkbox]:focus
      {
          outline: 1px solid rgba(0, 0, 0, 0.2);
      }
      
      INPUT[type=checkbox]
      {
          background-color: #DDD;
          border-radius: 2px;
          appearance: none;
          -webkit-appearance: none;
          -moz-appearance: none;
          width: 17px;
          height: 17px;
          cursor: pointer;
          position: relative;
          top: 5px;
      }
      
      INPUT[type=checkbox]:checked
      {
          background-color: #409fd6;
          background: #409fd6 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
      }
      <form>
        <label><input type="checkbox"> I Agree To Terms &amp; Conditions</label>
      </form>

      【讨论】:

      • 好主意,沃洛迈克。一些改进: 1) 将宽度和高度设置为 1em,将顶部设置为 0.2em,使其可随字体大小缩放。 2)将背景设置为中心/覆盖以随尺寸缩放。此外,代码中的 background-color 是多余的。 3) 删除cursor: pointer - 保留默认行为并让用户在他们的样式表中设置它。
      • 您也可以只使用:all: unset,作为复选框,它具有几乎相同的开箱即用支持,不需要特定于浏览器的标志,以及 appearance 附带的警告. :)
      • 这是迄今为止最简单的解决方案,可在 2022 年适用于 Chrome、Firefox 和 Safari。谢谢老哥!
      【解决方案9】:

      易于实施且易于定制的解决方案

      经过大量搜索和测试后,我得到了这个解决方案,它易于实现且更易于定制。 在此解决方案中

      1. 您不需要外部库和文件
      2. 您不需要添加 页面中的额外 HTML
      3. 您无需更改复选框名称 和身份证

      简单地将流动的 CSS 放在页面顶部,所有的复选框样式都会改变如下:

      input[type=checkbox] {
        transform: scale(1.5);
      }
      
      input[type=checkbox] {
        width: 30px;
        height: 30px;
        margin-right: 8px;
        cursor: pointer;
        font-size: 17px;
        visibility: hidden;
      }
      
      input[type=checkbox]:after,
      input[type=checkbox]::after {
        content: " ";
        background-color: #fff;
        display: inline-block;
        margin-left: 10px;
        padding-bottom: 5px;
        color: #00BFF0;
        width: 22px;
        height: 25px;
        visibility: visible;
        border: 1px solid #00BFF0;
        padding-left: 3px;
        border-radius: 5px;
      }
      
      input[type=checkbox]:checked:after,
      input[type=checkbox]:checked::after {
        content: "\2714";
        padding: -5px;
        font-weight: bold;
      }
      <input type="checkbox" id="checkbox1" />
      <label for="checkbox1">Checkbox</label>

      【讨论】:

      • 不错的解决方案。但我没有看到它在 Firefox、IE 或 Edge 上运行(没有复选框)
      • @Jono 我已经更新了答案,请立即尝试。
      • @DeanVanGreunen 在 Firefox(Mac,97.0.2)上仍然没有复选框 - 我无法检查 IE 或 Edge
      【解决方案10】:

      您可以使用label 元素为复选框设置样式,示例如下:

      .checkbox > input[type=checkbox] {
        visibility: hidden;
      }
      
      .checkbox {
        position: relative;
        display: block;
        width: 80px;
        height: 26px;
        margin: 0 auto;
        background: #FFF;
        border: 1px solid #2E2E2E;
        border-radius: 2px;
        -webkit-border-radius: 2px;
        -moz-border-radius: 2px;
      }
      
      .checkbox:after {
        position: absolute;
        display: inline;
        right: 10px;
        content: 'no';
        color: #E53935;
        font: 12px/26px Arial, sans-serif;
        font-weight: bold;
        text-transform: capitalize;
        z-index: 0;
      }
      
      .checkbox:before {
        position: absolute;
        display: inline;
        left: 10px;
        content: 'yes';
        color: #43A047;
        font: 12px/26px Arial, sans-serif;
        font-weight: bold;
        text-transform: capitalize;
        z-index: 0;
      }
      
      .checkbox label {
        position: absolute;
        display: block;
        top: 3px;
        left: 3px;
        width: 34px;
        height: 20px;
        background: #2E2E2E;
        cursor: pointer;
        transition: all 0.5s linear;
        -webkit-transition: all 0.5s linear;
        -moz-transition: all 0.5s linear;
        border-radius: 2px;
        -webkit-border-radius: 2px;
        -moz-border-radius: 2px;
        z-index: 1;
      }
      
      .checkbox input[type=checkbox]:checked + label {
        left: 43px;
      }
      <div class="checkbox">
        <input id="checkbox1" type="checkbox" value="1" />
        <label for="checkbox1"></label>
      </div>

      上面的代码还有一个 FIDDLE。请注意,某些 CSS 在旧版本的浏览器中不起作用,但我确信那里有一些精美的 JavaScript 示例!

      【讨论】:

      • 在复选框有中标标签的地方如何使用?
      • @Metaphor 只需添加第二个标签。您可以将多个标签应用于同一元素(例如,它们可以使用相同的 for 属性值)。
      【解决方案11】:

      CSS Basic User Interface Module Level 4(最终)通过一个名为 accent-color 的新解决方案添加了对此的支持,它实际上非常简单,与这里的几乎所有其他答案不同:

      input {
          accent-color: rebeccapurple;
      }
      &lt;input type="checkbox" /&gt;

      只需将您想要的任何 CSS 颜色(例如命名值、十六进制代码等)设置为 accent-color 的值,它就会被应用。

      目前适用于 Chrome (v93+)、Edge (v93+)、Firefox (v92+)、Opera (v79+) 和 Safari 的技术预览版 (v135+)。 Safari 的生产版本仍然缺乏支持。

      注意:Edge、Chrome 和 Opera(可能还有 Safari 技术预览版;我无法测试)目前也不支持通过 rgba() 的 alpha 通道值(rgba() 的 RGB 值仍然“有效” "; alpha 通道将被浏览器简单地忽略)。请参阅MDN Browser Support 了解更多信息。

      【讨论】:

      • 不错!但是,accent-color: rgba(0,0,0,0.1) 会不会忽略 alpha 通道?我的复选框背景只是黑色。
      • @Flippowitsch 在 Firefox 92.0 上,我看到了正确的 alpha 通道。看起来 Chrome 93 和 Edge 93 还不支持 alpha 通道……好消息!我会更新我的答案。
      • 使用 #3cc7a7 例如作为十六进制将图标变为黑色而不是白色..
      • @Chrillewoodz 图标?如果您指的是复选框,它会将复选框变成薄荷绿色(因为 #3cc7a7 是这种颜色):jsfiddle.net/TylerH/vuox3kzg
      • 我的意思是复选标记图标。背景变为绿色,但图标变为黑色。
      【解决方案12】:

      您可以避免添加额外的标记。通过设置 CSS appearance,这适用于桌面版 IE(但适用于 Windows Phone 和 Microsoft Edge 的 IE)以外的任何地方:

      input[type="checkbox"] {
        -webkit-appearance: none;
        -moz-appearance: none;
        appearance: none;
      
        /* Styling checkbox */
        width: 16px;
        height: 16px;
        background-color: red;
      }
      
      input[type="checkbox"]:checked {
        background-color: green;
      }
      &lt;input type="checkbox" /&gt;

      【讨论】:

      • 我喜欢这种方法——它有点笨拙,因为你不应该真正在 css 中使用外观,但它比之前和之后使用的其他一些答案要干净得多。对于这样的事情,我觉得 JavaScript 完全是矫枉过正。
      【解决方案13】:

      最近我发现了一个非常有趣的解决方案。

      您可以使用appearance: none; 关闭复选框的默认样式,然后按照here (Example 4) 的描述在上面写下您自己的样式。

      input[type=checkbox] {
        width: 23px;
        height: 23px;
        -webkit-appearance: none;
        -moz-appearance: none;
        appearance: none;
        margin-right: 10px;
        background-color: #878787;
        outline: 0;
        border: 0;
        display: inline-block;
        -webkit-box-shadow: none !important;
        -moz-box-shadow: none !important;
        box-shadow: none !important;
      }
      
      input[type=checkbox]:focus {
        outline: none;
        border: none !important;
        -webkit-box-shadow: none !important;
        -moz-box-shadow: none !important;
        box-shadow: none !important;
      }
      
      input[type=checkbox]:checked {
        background-color: green;
        text-align: center;
        line-height: 15px;
      }
      &lt;input type="checkbox"&gt;

      不幸的是,appearance 选项的浏览器支持非常糟糕。根据我的个人测试,我只让 Opera 和 Chrome 正常工作。但是,当有更好的支持或您只想使用 Chrome/Opera 时,这将是保持简单的方法。

      Example JSFiddle

      "Can I use?" link

      【讨论】:

      • 确实 appearance 正是我们需要的;请记住它"is non-standard and is not on a standards track"
      • 我添加了更多样式,以使其更接近 chrome 复选框。所以它很容易互换:-jsfiddle.net/inspiraller/g8mo1nh3/1
      • 这里的缺点之一是您丢失了“复选框”的“检查”部分。它现在只是一个可以改变颜色的框,从用户体验/可访问性的角度来看,它是什么以及单击它时发生的情况远不太清楚。
      【解决方案14】:

      我更喜欢使用图标字体(例如 FontAwesome),因为使用 CSS 修改它们的颜色很容易,而且它们在高像素密度设备上的缩放效果非常好。所以这是另一个纯 CSS 变体,使用与上述类似的技术。

      (下面是静态图像,因此您可以将结果可视化;请参阅the JSFiddle 了解交互式版本。)

      与其他解决方案一样,它使用label 元素。相邻的span 包含我们的复选框字符。

      span.bigcheck-target {
        font-family: FontAwesome; /* Use an icon font for the checkbox */
      }
      
      input[type='checkbox'].bigcheck {
        position: relative;
        left: -999em; /* Hide the real checkbox */
      }
      
      input[type='checkbox'].bigcheck + span.bigcheck-target:after {
        content: "\f096"; /* In fontawesome, is an open square (fa-square-o) */
      }
      
      input[type='checkbox'].bigcheck:checked + span.bigcheck-target:after {
        content: "\f046"; /* fontawesome checked box (fa-check-square-o) */
      }
      
      /* ==== Optional - colors and padding to make it look nice === */
      body {
        background-color: #2C3E50;
        color: #D35400;
        font-family: sans-serif;
        font-weight: 500;
        font-size: 4em; /* Set this to whatever size you want */
      }
      
      span.bigcheck {
        display: block;
        padding: 0.5em;
      }
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
      
      <span class="bigcheck">
        <label class="bigcheck">
          Cheese
          <input type="checkbox" class="bigcheck" name="cheese" value="yes" />
          <span class="bigcheck-target"></span>
        </label>
      </span>

      这是JSFiddle

      【讨论】:

      • ....您所描述的与 Bhushan wagh、Jake、Jonathan Hodgson 和 Blake 之前的回答相同;)
      • @SW4 我已经提到了这个事实,除了这个答案使用图标字体(以前的答案都没有)。第一段很清楚。
      • 你需要将font-family: FontAwesome;替换为font-family: 'Font Awesome\ 5 Free';,如果你想让它在新版本中工作,你需要更新unicode内容。
      【解决方案15】:

      我的解决方案

      input[type="checkbox"] {
        cursor: pointer;
        -webkit-appearance: none;
        -moz-appearance: none;
        appearance: none;
        outline: 0;
        background: lightgray;
        height: 16px;
        width: 16px;
        border: 1px solid white;
      }
      
      input[type="checkbox"]:checked {
        background: #2aa1c0;
      }
      
      input[type="checkbox"]:hover {
        filter: brightness(90%);
      }
      
      input[type="checkbox"]:disabled {
        background: #e6e6e6;
        opacity: 0.6;
        pointer-events: none;
      }
      
      input[type="checkbox"]:after {
        content: '';
        position: relative;
        left: 40%;
        top: 20%;
        width: 15%;
        height: 40%;
        border: solid #fff;
        border-width: 0 2px 2px 0;
        transform: rotate(45deg);
        display: none;
      }
      
      input[type="checkbox"]:checked:after {
        display: block;
      }
      
      input[type="checkbox"]:disabled:after {
        border-color: #7b7b7b;
      }
      <input type="checkbox"><br>
      <input type="checkbox" checked><br>
      <input type="checkbox" disabled><br>
      <input type="checkbox" disabled checked><br>

      【讨论】:

      • 如果有人能告诉我为什么我的文字没有对齐,我很想知道! CSS初学者在这里。
      • 检查了整个线程和外观似乎是关键以及之后。此外,如果有人需要更大的复选框,那么这个解决方案就可以了。只需使用顶部、左侧、宽度、高度和边框宽度即可。根据 caniuse.com 在现代浏览器中工作。我在 2021 年 5 月为我未来的自己写这篇评论。 :)
      【解决方案16】:

      您可以在现代浏览器上简单地使用appearance: none,这样就没有默认样式并且您的所有样式都可以正确应用:

      input[type=checkbox] {
        -webkit-appearance: none;
        -moz-appearance: none;
        appearance: none;
        display: inline-block;
        width: 2em;
        height: 2em;
        border: 1px solid gray;
        outline: none;
        vertical-align: middle;
      }
      
      input[type=checkbox]:checked {
        background-color: blue;
      }
      

      【讨论】:

      • 这复制了 Joost 2015 年回答中的解决方案。
      • @TylerH 你知道copy是什么意思吗?我们都使用appearance 这一事实并不意味着答案是相同的。我的代码肯定更小更干净,我还补充说该解决方案适用于现代浏览器。
      • 事实上,我知道复制是什么意思。 Joost's answer 建议使用 appearance: none 作为解决方案。这个答案还建议使用appearance: none 作为解决方案。由于它提出了相同的解决方案,因此它是一个副本。它不一定是逐字符的传真才能成为副本。下次,请在发布您自己的答案之前阅读所有现有答案,以避免简单地重复信息。
      【解决方案17】:

      这是一个简单的 CSS 解决方案,没有任何 jQuery 或 JavaScript 代码。

      我正在使用 FontAwseome 图标,但您可以使用任何图像

      input[type=checkbox] {
        display: inline-block;
        font-family: FontAwesome;
        font-style: normal;
        font-weight: normal;
        line-height: 1;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        visibility: hidden;
        font-size: 14px;
      }
      
      input[type=checkbox]:before {
        content: @fa-var-square-o;
        visibility: visible;
        /*font-size: 12px;*/
      }
      
      input[type=checkbox]:checked:before {
        content: @fa-var-check-square-o;
      }
      

      【讨论】:

      • 与大多数其他答案不同,此答案不需要创建额外的 labelspan 元素。它只是工作!
      • 你能展示一个例子或演示,或者至少是 HTML 部分,这个 CSS 代码可以使用吗? @aWebDeveloper
      • @aWebDeveloper 进行愚蠢的编辑以将答案或问题添加到主页是违反规则的。
      • @aWebDeveloper 您编辑了一个针对非活动问题的旧答案,这会将其放到首页并提供直接指向您答案的链接。如果您有相关信息要在答案中添加或更改,这很好。您所做的只是将您的一个句子嵌入到引用块中,这对任何人都没有用。
      • 应该可以工作 @VadimOvchinnikov...这里没有什么是特定于 chrome 的
      【解决方案18】:

      根据我的谷歌搜索,这是复选框样式的最简单方法。只需根据您的设计添加:after:checked:after CSS。

      body{
        background: #DDD;
      }
      span{
        margin-left: 30px;
      }
      input[type=checkbox] {
          cursor: pointer;
          font-size: 17px;
          visibility: hidden;
          position: absolute;
          top: 0;
          left: 0;
          transform: scale(1.5);
      }
      
      input[type=checkbox]:after {
          content: " ";
          background-color: #fff;
          display: inline-block;
          color: #00BFF0;
          width: 14px;
          height: 19px;
          visibility: visible;
          border: 1px solid #FFF;
          padding: 0 3px;
          margin: 2px 0;
          border-radius: 8px;
          box-shadow: 0 0 15px 0 rgba(0,0,0,0.08), 0 0 2px 0 rgba(0,0,0,0.16);
      }
      
      input[type=checkbox]:checked:after {
          content: "\2714";
          display: unset;
          font-weight: bold;
      }
      &lt;input type="checkbox"&gt; &lt;span&gt;Select Text&lt;/span&gt;

      【讨论】:

        【解决方案19】:

        哎呀!所有这些变通方法都让我得出结论,如果你想设置 HTML 复选框的样式,它就很糟糕。

        作为预警,这不是 CSS 实现。我只是想分享一下我想出的解决方法,以防其他人发现它有用。


        我使用了 HTML5 canvas 元素。

        这样做的好处是您不必使用外部图像,并且可能会节省一些带宽。

        不利的一面是,如果浏览器由于某种原因无法正确呈现它,那么就没有后备方案。尽管这在 2017 年是否仍然是一个问题还有待商榷。

        更新

        我发现旧代码很丑,所以我决定重写它。

        Object.prototype.create = function(args){
            var retobj = Object.create(this);
        
            retobj.constructor(args || null);
        
            return retobj;
        }
        
        var Checkbox = Object.seal({
            width: 0,
            height: 0,
            state: 0,
            document: null,
            parent: null,
            canvas: null,
            ctx: null,
        
            /*
             * args:
             * name      default             desc.
             *
             * width     15                  width
             * height    15                  height
             * document  window.document     explicit document reference
             * target    this.document.body  target element to insert checkbox into
             */
            constructor: function(args){
                if(args === null)
                    args = {};
        
                this.width = args.width || 15;
                this.height = args.height || 15;
                this.document = args.document || window.document;
                this.parent = args.target || this.document.body;
                this.canvas = this.document.createElement("canvas");
                this.ctx = this.canvas.getContext('2d');
        
                this.canvas.width = this.width;
                this.canvas.height = this.height;
                this.canvas.addEventListener("click", this.ev_click(this), false);
                this.parent.appendChild(this.canvas);
                this.draw();
            },
        
            ev_click: function(self){
                return function(unused){
                    self.state = !self.state;
                    self.draw();
                }
            },
        
            draw_rect: function(color, offset){
                this.ctx.fillStyle = color;
                this.ctx.fillRect(offset, offset,
                        this.width - offset * 2, this.height - offset * 2);
            },
        
            draw: function(){
                this.draw_rect("#CCCCCC", 0);
                this.draw_rect("#FFFFFF", 1);
        
                if(this.is_checked())
                    this.draw_rect("#000000", 2);
            },
        
            is_checked: function(){
                return !!this.state;
            }
        });
        

        这是working demo

        新版本使用原型和差分继承来创建一个用于创建复选框的高效系统。创建一个复选框:

        var my_checkbox = Checkbox.create();
        

        这将立即将复选框添加到 DOM 并连接事件。查询复选框是否被选中:

        my_checkbox.is_checked(); // True if checked, else false
        

        另外需要注意的是,我摆脱了循环。

        更新 2

        我在上次更新中没有提到的一点是,使用画布比仅仅制作一个看起来随心所欲的复选框更有优势。如果您愿意,您还可以创建 多状态 复选框。

        Object.prototype.create = function(args){
            var retobj = Object.create(this);
        
            retobj.constructor(args || null);
        
            return retobj;
        }
        
        Object.prototype.extend = function(newobj){
            var oldobj = Object.create(this);
        
            for(prop in newobj)
                oldobj[prop] = newobj[prop];
        
            return Object.seal(oldobj);
        }
        
        var Checkbox = Object.seal({
            width: 0,
            height: 0,
            state: 0,
            document: null,
            parent: null,
            canvas: null,
            ctx: null,
        
            /*
             * args:
             * name      default             desc.
             *
             * width     15                  width
             * height    15                  height
             * document  window.document     explicit document reference
             * target    this.document.body  target element to insert checkbox into
             */
            constructor: function(args){
                if(args === null)
                    args = {};
        
                this.width = args.width || 15;
                this.height = args.height || 15;
                this.document = args.document || window.document;
                this.parent = args.target || this.document.body;
                this.canvas = this.document.createElement("canvas");
                this.ctx = this.canvas.getContext('2d');
        
                this.canvas.width = this.width;
                this.canvas.height = this.height;
                this.canvas.addEventListener("click", this.ev_click(this), false);
                this.parent.appendChild(this.canvas);
                this.draw();
            },
        
            ev_click: function(self){
                return function(unused){
                    self.state = !self.state;
                    self.draw();
                }
            },
        
            draw_rect: function(color, offsetx, offsety){
                this.ctx.fillStyle = color;
                this.ctx.fillRect(offsetx, offsety,
                        this.width - offsetx * 2, this.height - offsety * 2);
            },
        
            draw: function(){
                this.draw_rect("#CCCCCC", 0, 0);
                this.draw_rect("#FFFFFF", 1, 1);
                this.draw_state();
            },
        
            draw_state: function(){
                if(this.is_checked())
                    this.draw_rect("#000000", 2, 2);
            },
        
            is_checked: function(){
                return this.state == 1;
            }
        });
        
        var Checkbox3 = Checkbox.extend({
            ev_click: function(self){
                return function(unused){
                    self.state = (self.state + 1) % 3;
                    self.draw();
                }
            },
        
            draw_state: function(){
                if(this.is_checked())
                    this.draw_rect("#000000", 2, 2);
        
                if(this.is_partial())
                    this.draw_rect("#000000", 2, (this.height - 2) / 2);
            },
        
            is_partial: function(){
                return this.state == 2;
            }
        });
        

        我稍微修改了最后一个 sn-p 中使用的Checkbox,使其更通用,从而可以使用具有 3 个状态的复选框“扩展”它。这是a demo。如您所见,它已经拥有比内置复选框更多的功能。

        在 JavaScript 和 CSS 之间进行选择时需要考虑的事项。

        陈旧、设计不佳的代码

        Working Demo

        首先,设置一个画布

        var canvas = document.createElement('canvas'),
            ctx = canvas.getContext('2d'),
            checked = 0; // The state of the checkbox
        canvas.width = canvas.height = 15; // Set the width and height of the canvas
        document.body.appendChild(canvas);
        document.body.appendChild(document.createTextNode(' Togglable Option'));
        

        接下来,设计一种让画布自行更新的方法。

        (function loop(){
          // Draws a border
          ctx.fillStyle = '#ccc';
          ctx.fillRect(0,0,15,15);
          ctx.fillStyle = '#fff';
          ctx.fillRect(1, 1, 13, 13);
          // Fills in canvas if checked
          if(checked){
            ctx.fillStyle = '#000';
            ctx.fillRect(2, 2, 11, 11);
          }
          setTimeout(loop, 1000/10); // Refresh 10 times per second
        })();
        

        最后一部分是使其具有交互性。幸运的是,这很简单:

        canvas.onclick = function(){
          checked = !checked;
        }
        

        这是你在 IE 中可能遇到问题的地方,因为它们在 JavaScript 中的事件处理模型很奇怪。


        我希望这对某人有所帮助;它绝对适合我的需求。

        【讨论】:

        • 请注意,Canvas 实现,作为复选框的模拟,允许比内置复选框更多的功能。例如,诸如“多状态”复选框之类的花哨的东西(即unchecked (e.g. unchecked -&gt; checked -&gt; "kinda" checked -&gt; unchecked;状态可以表示“显式假”、“显式真”、“使用默认值”等)。我正在考虑在答案中添加一个示例。
        • 在我看来这个想法很糟糕。
        • @Neil 请详细说明
        • 为什么要重新发明轮子?
        • @Neil 为什么重新发明轮子? NIH 并不总是一件坏事,尤其是当它提供了用现有技术不可能或愚蠢地实现的优势时。所以这是一个你是否愿意处理内置复选框的问题。如果我想让它们与我的网站或应用程序的视觉语言相融合,我想要完全控制。因此,除非有人制作了一个轻量级且易于使用的独立 UI 库,否则我个人更喜欢在这里发明我的轮子。其他人可能不会,但这并不会使我的答案无效。
        【解决方案20】:

        使用纯 CSS3 修改复选框样式,不需要任何 JS&HTML 操作。

        .form input[type="checkbox"]:before {
          display: inline-block;
          font: normal normal normal 14px/1 FontAwesome;
          font-size: inherit;
          text-rendering: auto;
          -webkit-font-smoothing: antialiased;
          content: "\f096";
          opacity: 1 !important;
          margin-top: -25px;
          appearance: none;
          background: #fff;
        }
        
        .form input[type="checkbox"]:checked:before {
          content: "\f046";
        }
        
        .form input[type="checkbox"] {
          font-size: 22px;
          appearance: none;
          -webkit-appearance: none;
          -moz-appearance: none;
        }
        <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
        
        <form class="form">
          <input type="checkbox" />
        </form>

        【讨论】:

        【解决方案21】:

        SCSS / SASS 实现

        更现代的方法

        对于那些使用 SCSS(或轻松转换为 SASS)的人,以下内容会有所帮助。实际上,在复选框旁边制作一个元素,这是您将设置样式的元素。单击复选框时,CSS 会重新设置姊妹元素的样式(为新的选中样式)。代码如下:

        label.checkbox {
          input[type="checkbox"] {
            visibility: hidden;
            display: block;
            height: 0;
            width: 0;
            position: absolute;
            overflow: hidden;
        
            &:checked + span {
              background: $accent;
            }
          }
        
          span {
            cursor: pointer;
            height: 15px;
            width: 15px;
            border: 1px solid $accent;
            border-radius: 2px;
            display: inline-block;
            transition: all 0.2s $interpol;
          }
        }
        <label class="checkbox">
            <input type="checkbox" />
            <span></span>
            Label text
        </label>

        【讨论】:

          【解决方案22】:

          也是一个简单轻量级的模板:

          input[type=checkbox] {
            cursor: pointer;
          }
          
          input[type=checkbox]:checked:before {
            content: "\2713";
            background: #fffed5;
            text-shadow: 1px 1px 1px rgba(0, 0, 0, .2);
            font-size: 20px;
            text-align: center;
            line-height: 8px;
            display: inline-block;
            width: 13px;
            height: 15px;
            color: #00904f;
            border: 1px solid #cdcdcd;
            border-radius: 4px;
            margin: -3px -3px;
            text-indent: 1px;
          }
          
          input[type=checkbox]:before {
            content: "\202A";
            background: #ffffff;
            text-shadow: 1px 1px 1px rgba(0, 0, 0, .2);
            font-size: 20px;
            text-align: center;
            line-height: 8px;
            display: inline-block;
            width: 13px;
            height: 15px;
            color: #00904f;
            border: 1px solid #cdcdcd;
            border-radius: 4px;
            margin: -3px -3px;
            text-indent: 1px;
          }
          <input type="checkbox" checked="checked">checked1<br>
          <input type="checkbox">unchecked2<br>
          <input type="checkbox" checked="checked" id="id1">
          <label for="id1">checked2+label</label><br>
          <label for="id2">unchecked2+label+rtl</label>
          <input type="checkbox" id="id2">
          <br>

          https://jsfiddle.net/rvgccn5b/

          【讨论】:

          • inputs 的伪元素仅在 Chrome 中受支持,您的代码在每个浏览器中的工作方式都不相同。
          【解决方案23】:

          我认为最简单的方法是设置 label 的样式并使 checkbox 不可见。

          HTML

          <input type="checkbox" id="first" />
          <label for="first">&nbsp;</label>
          

          CSS

          checkbox {
            display: none;
          }
          
          checkbox + label {
            /* Style for checkbox normal */
            width: 16px;
            height: 16px;
          }
          
          checkbox::checked + label,
          label.checked {
            /* Style for checkbox checked */
          }
          

          checkbox,即使它是隐藏的,仍然可以访问,并且它的值将在提交表单时发送。对于旧浏览器,您可能需要将 label 的类更改为使用 JavaScript 进行检查,因为我认为旧版本的 Internet Explorer 无法理解 checkbox 上的 ::checked

          【讨论】:

          • 你的答案和我的答案到底有什么不同?
          • @BlakePettersson 你的是正确的, ::checked 是错误的(我什至尝试过以防万一它也被允许);)
          • 这是一个糟糕的答案。 (a) ::checked 错误——应该是 :checked。 (b) checkbox 错误——应该是 [type=checkbox]
          【解决方案24】:

          不需要 JavaScript 或 jQuery。

          以简单的方式更改您的复选框样式。

          input[type="checkbox"] {
            display: none;
            border: none !important;
            box-shadow: none !important;
          }
          
          input[type="checkbox"] + label span {
            background: url(http://imgh.us/uncheck.png);
            width: 49px;
            height: 49px;
            display: inline-block;
            vertical-align: middle;
          }
          
          input[type="checkbox"]:checked + label span {
            background: url(http://imgh.us/check_2.png);
            width: 49px;
            height: 49px;
            vertical-align: middle;
          }
          <input type="checkbox" id="option" />
          <label for="option"> <span></span> Click me </label>

          Here is a JSFiddle link

          【讨论】:

          【解决方案25】:

          带有 CSS 的自定义复选框(WebKit 浏览器解决方案仅限 Chrome、Safari、移动浏览器)

          <input type="checkbox" id="cardAccptance" name="cardAccptance" value="Yes">
          <label for="cardAccptance" class="bold"> Save Card for Future Use</label>
          

          CSS:

              /* The checkbox-cu */
              
              .checkbox-cu {
                  display: block;
                  position: relative;
                  padding-left: 35px;
                  margin-bottom: 0;
                  cursor: pointer;
                  font-size: 16px;
                  -webkit-user-select: none;
                  -moz-user-select: none;
                  -ms-user-select: none;
                  user-select: none;
              }
              
              
              /* Hide the browser's default checkbox-cu */
              
              .checkbox-cu input {
                  position: absolute;
                  opacity: 0;
                  cursor: pointer;
                  height: 0;
                  width: 0;
              }
              
              
              /* Create a custom checkbox-cu */
              
              .checkmark {
                  position: absolute;
                  top: 4px;
                  left: 0;
                  height: 20px;
                  width: 20px;
                  background-color: #eee;
                  border: 1px solid #999;
                  border-radius: 0;
                  box-shadow: none;
              }
              
              
              /* On mouse-over, add a grey background color */
              
              .checkbox-cu:hover input~.checkmark {
                  background-color: #ccc;
              }
              
              
              /* When the checkbox-cu is checked, add a blue background */
              
              .checkbox-cu input:checked~.checkmark {
                  background-color: transparent;
              }
              
              
              /* Create the checkmark/indicator (hidden when not checked) */
              
              .checkmark:after {
                  content: "";
                  position: absolute;
                  display: none;
              }
              
              
              /* Show the checkmark when checked */
              
              .checkbox-cu input:checked~.checkmark:after {
                  display: block;
              }
              
              
              /* Style the checkmark/indicator */
              
              .checkbox-cu .checkmark::after {
                  left: 7px;
                  top: 3px;
                  width: 6px;
                  height: 9px;
                  border: solid #28a745;
                  border-width: 0 2px 2px 0;
                  -webkit-transform: rotate(45deg);
                  -ms-transform: rotate(45deg);
                  transform: rotate(45deg);
                  z-index: 100;
              }
          

          【讨论】:

            【解决方案26】:

            通过将Materialize 与自定义样式表一起使用,您可以实现如下效果:

            CSS 代码

            .custom_checkbox[type="checkbox"]:checked + span:not(.lever)::before {
              border: 2px solid transparent;
              border-bottom: 2px solid #ffd600;
              border-right: 2px solid #ffd600;
              background: transparent;
            }
            

            HTML 代码

            <label>
                <input type="checkbox" class="custom_checkbox" />
                <span>Text</span>
            </label>
            

            演示

            JSFiddle demo

            【讨论】:

              【解决方案27】:

              这是最简单的方法,您可以选择哪些复选框来赋予此样式。

              CSS:

              .check-box input {
                display: none;
              }
              
              .check-box span:before {
                content: ' ';
                width: 20px;
                height: 20px;
                display: inline-block;
                background: url("unchecked.png");
              }
              
              .check-box input:checked + span:before {
                background: url("checked.png");
              }
              

              HTML:

              <label class="check-box">
                <input type="checkbox">
                <span>Check box Text</span>
              </label>
              

              【讨论】:

                【解决方案28】:

                这是一个纯 CSS/HTML 版本,根本不需要 jQuery 或 JavaScript,简单干净的 HTML 和非常简单短的 CSS。

                这里是 JSFiddle

                http://jsfiddle.net/v71kn3pr/

                这里是 HTML:

                <div id="myContainer">
                    <input type="checkbox" name="myCheckbox" id="myCheckbox_01_item" value="red" />
                    <label for="myCheckbox_01_item" class="box"></label>
                    <label for="myCheckbox_01_item" class="text">I accept the Terms of Use.</label>
                </div>
                

                这里是 CSS

                #myContainer {
                    outline: black dashed 1px;
                    width: 200px;
                }
                #myContainer input[type="checkbox"][name="myCheckbox"] {
                    display: none;
                }
                #myContainer input[type="checkbox"][name="myCheckbox"]:not(:checked) + label.box {
                    display: inline-block;
                    width: 25px;
                    height: 25px;
                    border: black solid 1px;
                    background: #FFF ;
                    margin: 5px 5px;
                }
                #myContainer input[type="checkbox"][name="myCheckbox"]:checked + label.box {
                    display: inline-block;
                    width: 25px;
                    height: 25px;
                    border: black solid 1px;
                    background: #F00;
                    margin: 5px 5px;
                }
                #myContainer input[type="checkbox"][name="myCheckbox"] + label + label.text {
                    font: normal 12px arial;
                    display: inline-block;
                    line-height: 27px;
                    vertical-align: top;
                    margin: 5px 0px;
                }
                

                这可以调整为能够拥有单独的单选或复选框、复选框组和单选按钮组。

                此 html/css 将允许您还捕获对标签的点击,因此即使您仅点击标签,复选框也会被选中和取消选中。

                这种类型的复选框/单选按钮完美地适用于任何形式,完全没有问题。也已经使用 PHP、ASP.NET (.aspx)、JavaServer FacesColdFusion 进行了测试。

                【讨论】:

                  【解决方案29】:

                  由于 Edge 和 Firefox 等浏览器不支持复选框输入标签上的 :before :after ,因此这里有一个纯 HTML 和 CSS 的替代方案。当然,您应该根据自己的要求编辑 CSS。

                  为复选框制作 HTML,如下所示:

                  <div class='custom-checkbox'>
                      <input type='checkbox' />
                      <label>
                          <span></span>
                          Checkbox label
                      </label>
                  </div>
                  

                  将此样式应用于复选框以更改颜色标签

                  <style>
                      .custom-checkbox {
                          position: relative;
                      }
                      .custom-checkbox input{
                          position: absolute;
                          left: 0;
                          top: 0;
                          height:15px;
                          width: 50px;    /* Expand the checkbox so that it covers */
                          z-index : 1;    /* the label and span, increase z-index to bring it over */
                          opacity: 0;     /* the label and set opacity to 0 to hide it. */
                      }
                      .custom-checkbox input+label {
                          position: relative;
                          left: 0;
                          top: 0;
                          padding-left: 25px;
                          color: black;
                      }
                      .custom-checkbox input+label span {
                          position: absolute;  /* a small box to display as checkbox */
                          left: 0;
                          top: 0;
                          height: 15px;
                          width: 15px;
                          border-radius: 2px;
                          border: 1px solid black;
                          background-color: white;
                      }
                      .custom-checkbox input:checked+label { /* change label color when checked */
                          color: orange;
                      }
                      .custom-checkbox input:checked+label span{ /* change span box color when checked */
                          background-color: orange;
                          border: 1px solid orange;
                      }
                  </style>
                  

                  【讨论】:

                    【解决方案30】:

                    这是一个示例,支持主题。这是一种带有 CSS 过渡的现代方法。绝对不需要 JavaScript。

                    我派生了这个comment中链接的以下代码;关于一个相关问题。

                    编辑:我添加了单选按钮,如 maxshuty suggests

                    const selector = '.grid-container > .grid-row > .grid-col[data-theme="retro"]';
                    const main = () => {
                      new CheckboxStyler().run(selector);
                      new RadioStyler().run(selector);
                    };
                    
                    /*
                     * This is only used to add the wrapper class and checkmark span to an existing DOM,
                     * to make this CSS work.
                     */
                    class AbstractInputStyler {
                      constructor(options) {
                        this.opts = options;
                      }
                      run(parentSelector) {
                        let wrapperClass = this.opts.wrapperClass;
                        let parent = document.querySelector(parentSelector) || document.getElementsByTagName('body')[0];
                        let labels = parent.querySelectorAll('label');
                        if (labels.length) labels.forEach(label => {
                          if (label.querySelector(`input[type="${this.opts._inputType}"]`)) {
                            if (!label.classList.contains(wrapperClass)) {
                              label.classList.add(wrapperClass);
                              label.appendChild(this.__createDefaultNode());
                            }
                          }
                        });
                        return this;
                      }
                      /* @protected */
                      __createDefaultNode() {
                        let checkmark = document.createElement('span');
                        checkmark.className = this.opts._activeClass;
                        return checkmark;
                      }
                    }
                    
                    class CheckboxStyler extends AbstractInputStyler {
                      constructor(options) {
                        super(Object.assign({
                          _inputType: 'checkbox',
                          _activeClass: 'checkmark'
                        }, CheckboxStyler.defaultOptions, options));
                      }
                    }
                    CheckboxStyler.defaultOptions = {
                      wrapperClass: 'checkbox-wrapper'
                    };
                    
                    class RadioStyler extends AbstractInputStyler {
                      constructor(options) {
                        super(Object.assign({
                          _inputType: 'radio',
                          _activeClass: 'pip'
                        }, RadioStyler.defaultOptions, options));
                      }
                    }
                    RadioStyler.defaultOptions = {
                      wrapperClass: 'radio-wrapper'
                    };
                    
                    main();
                    /* Theming */
                    
                    :root {
                      --background-color: #FFF;
                      --font-color: #000;
                      --checkbox-default-background: #EEE;
                      --checkbox-hover-background: #CCC;
                      --checkbox-disabled-background: #AAA;
                      --checkbox-selected-background: #1A74BA;
                      --checkbox-selected-disabled-background: #6694B7;
                      --checkbox-checkmark-color: #FFF;
                      --checkbox-checkmark-disabled-color: #DDD;
                    }
                    
                    [data-theme="dark"] {
                      --background-color: #111;
                      --font-color: #EEE;
                      --checkbox-default-background: #222;
                      --checkbox-hover-background: #444;
                      --checkbox-disabled-background: #555;
                      --checkbox-selected-background: #2196F3;
                      --checkbox-selected-disabled-background: #125487;
                      --checkbox-checkmark-color: #EEE;
                      --checkbox-checkmark-disabled-color: #999;
                    }
                    
                    [data-theme="retro"] {
                      --background-color: #FFA;
                      --font-color: #000;
                      --checkbox-default-background: #EEE;
                      --checkbox-hover-background: #FFF;
                      --checkbox-disabled-background: #BBB;
                      --checkbox-selected-background: #EEE;
                      --checkbox-selected-disabled-background: #BBB;
                      --checkbox-checkmark-color: #F44;
                      --checkbox-checkmark-disabled-color: #D00;
                    }
                    
                    
                    /* General styles */
                    
                    html {
                      width: 100%;
                      height: 100%;
                    }
                    
                    body {
                      /*background: var(--background-color); -- For demo, moved to column. */
                      /*color:      var(--font-color);       -- For demo, moved to column. */
                      background: #777;
                      width: calc(100% - 0.5em);
                      height: calc(100% - 0.5em);
                      padding: 0.25em;
                    }
                    
                    h1 {
                      font-size: 1.33em !important;
                    }
                    
                    h2 {
                      font-size: 1.15em !important;
                      margin-top: 1em;
                    }
                    
                    
                    /* Grid style - using flex */
                    
                    .grid-container {
                      display: flex;
                      height: 100%;
                      flex-direction: column;
                      flex: 1;
                    }
                    
                    .grid-row {
                      display: flex;
                      flex-direction: row;
                      flex: 1;
                      margin: 0.25em 0;
                    }
                    
                    .grid-col {
                      display: flex;
                      flex-direction: column;
                      height: 100%;
                      padding: 0 1em;
                      flex: 1;
                      margin: 0 0.25em;
                      /* If not demo, remove and uncomment the body color rules */
                      background: var(--background-color);
                      color: var(--font-color);
                    }
                    
                    .grid-cell {
                      width: 100%;
                      height: 100%;
                    }
                    
                    
                    /* The checkbox wrapper */
                    
                    .checkbox-wrapper,
                    .radio-wrapper {
                      display: block;
                      position: relative;
                      padding-left: 1.5em;
                      margin-bottom: 0.5em;
                      cursor: pointer;
                      -webkit-user-select: none;
                      -moz-user-select: none;
                      -ms-user-select: none;
                      user-select: none;
                    }
                    
                    
                    /* Hide the browser's default checkbox and radio buttons */
                    
                    .checkbox-wrapper input[type="checkbox"] {
                      position: absolute;
                      opacity: 0;
                      cursor: pointer;
                      height: 0;
                      width: 0;
                    }
                    
                    .radio-wrapper input[type="radio"] {
                      position: absolute;
                      opacity: 0;
                      cursor: pointer;
                      height: 0;
                      width: 0;
                    }
                    
                    
                    /* Create a custom checkbox */
                    
                    .checkbox-wrapper .checkmark {
                      position: absolute;
                      top: 0;
                      left: 0;
                      height: 1em;
                      width: 1em;
                      background-color: var(--checkbox-default-background);
                      transition: all 0.2s ease-in;
                    }
                    
                    .radio-wrapper .pip {
                      position: absolute;
                      top: 0;
                      left: 0;
                      height: 1em;
                      width: 1em;
                      border-radius: 50%;
                      background-color: var(--checkbox-default-background);
                      transition: all 0.2s ease-in;
                    }
                    
                    
                    /* Disabled style */
                    
                    .checkbox-wrapper input[type="checkbox"]:disabled~.checkmark,
                    .radio-wrapper input[type="radio"]:disabled~.pip {
                      cursor: not-allowed;
                      background-color: var(--checkbox-disabled-background);
                      color: var(--checkbox-checkmark-disabled-color);
                    }
                    
                    .checkbox-wrapper input[type="checkbox"]:disabled~.checkmark:after,
                    .radio-wrapper input[type="radio"]:disabled~.pip:after {
                      color: var(--checkbox-checkmark-disabled-color);
                    }
                    
                    .checkbox-wrapper input[type="checkbox"]:disabled:checked~.checkmark,
                    .radio-wrapper input[type="radio"]:disabled:checked~.pip {
                      background-color: var(--checkbox-selected-disabled-background);
                    }
                    
                    
                    /* On mouse-over, add a grey background color */
                    
                    .checkbox-wrapper:hover input[type="checkbox"]:not(:disabled):not(:checked)~.checkmark,
                    .radio-wrapper:hover input[type="radio"]:not(:disabled):not(:checked)~.pip {
                      background-color: var(--checkbox-hover-background);
                    }
                    
                    
                    /* When the checkbox is checked, add a blue background */
                    
                    .checkbox-wrapper input[type="checkbox"]:checked~.checkmark,
                    .radio-wrapper input[type="radio"]:checked~.pip {
                      background-color: var(--checkbox-selected-background);
                    }
                    
                    
                    /* Create the checkmark/indicator (hidden when not checked) */
                    
                    .checkbox-wrapper .checkmark:after {
                      display: none;
                      width: 100%;
                      position: absolute;
                      text-align: center;
                      content: "\2713";
                      color: var(--checkbox-checkmark-color);
                      line-height: 1.1em;
                    }
                    
                    .radio-wrapper .pip:after {
                      display: none;
                      width: 100%;
                      position: absolute;
                      text-align: center;
                      content: "\2022";
                      color: var(--checkbox-checkmark-color);
                      font-size: 1.5em;
                      top: -0.2em;
                    }
                    
                    
                    /* Show the checkmark when checked */
                    
                    .checkbox-wrapper input[type="checkbox"]:checked~.checkmark:after {
                      display: block;
                      line-height: 1.1em;
                    }
                    
                    .radio-wrapper input[type="radio"]:checked~.pip:after {
                      display: block;
                      line-height: 1.1em;
                    }
                    <link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" rel="stylesheet" />
                    <div class="grid-container">
                      <div class="grid-row">
                        <div class="grid-col">
                          <div class="grid-cell">
                            <h1>Pure CSS</h1>
                            <h2>Checkbox</h2>
                            <label class="checkbox-wrapper">One
                              <input type="checkbox" checked="checked">
                              <span class="checkmark"></span>
                            </label>
                            <label class="checkbox-wrapper">Two
                              <input type="checkbox">
                              <span class="checkmark"></span>
                            </label>
                            <label class="checkbox-wrapper">Three
                              <input type="checkbox" checked disabled>
                              <span class="checkmark"></span>
                            </label>
                            <label class="checkbox-wrapper">Four
                              <input type="checkbox" disabled>
                              <span class="checkmark"></span>
                            </label>
                            <h2>Radio</h2>
                            <label class="radio-wrapper">One
                              <input type="radio" name="group-x">
                              <span class="pip"></span>
                            </label>
                            <label class="radio-wrapper">Two
                              <input type="radio" name="group-x">
                              <span class="pip"></span>
                            </label>
                            <label class="radio-wrapper">Three
                              <input type="radio" name="group-x" checked disabled>
                              <span class="pip"></span>
                            </label>
                            <label class="radio-wrapper">Four
                              <input type="radio" name="group-x" disabled>
                              <span class="pip"></span>
                            </label>
                          </div>
                        </div>
                        <div class="grid-col" data-theme="dark">
                          <div class="grid-cell">
                            <h1>Pure CSS</h1>
                            <h2>Checkbox</h2>
                            <label class="checkbox-wrapper">One
                              <input type="checkbox" checked="checked">
                              <span class="checkmark"></span>
                            </label>
                            <label class="checkbox-wrapper">Two
                              <input type="checkbox">
                              <span class="checkmark"></span>
                            </label>
                            <label class="checkbox-wrapper">Three
                              <input type="checkbox" checked disabled>
                              <span class="checkmark"></span>
                            </label>
                            <label class="checkbox-wrapper">Four
                              <input type="checkbox" disabled>
                              <span class="checkmark"></span>
                            </label>
                            <h2>Radio</h2>
                            <label class="radio-wrapper">One
                              <input type="radio" name="group-y">
                              <span class="pip"></span>
                            </label>
                            <label class="radio-wrapper">Two
                              <input type="radio" name="group-y">
                              <span class="pip"></span>
                            </label>
                            <label class="radio-wrapper">Three
                              <input type="radio" name="group-y" checked disabled>
                              <span class="pip"></span>
                            </label>
                            <label class="radio-wrapper">Four
                              <input type="radio" name="group-y" disabled>
                              <span class="pip"></span>
                            </label>
                          </div>
                        </div>
                        <div class="grid-col" data-theme="retro">
                          <div class="grid-cell">
                            <h1>JS + CSS</h1>
                            <h2>Checkbox</h2>
                            <label>One   <input type="checkbox" checked="checked"></label>
                            <label>Two   <input type="checkbox"></label>
                            <label>Three <input type="checkbox" checked disabled></label>
                            <label>Four  <input type="checkbox" disabled></label>
                            <h2>Radio</h2>
                            <label>One   <input type="radio" name="group-z" checked="checked"></label>
                            <label>Two   <input type="radio" name="group-z"></label>
                            <label>Three <input type="radio" name="group-z" checked disabled></label>
                            <label>Four  <input type="radio" name="group-z" disabled></label>
                          </div>
                        </div>
                      </div>
                    </div>

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 2014-06-11
                      • 2014-09-14
                      • 1970-01-01
                      • 2010-12-12
                      • 2014-02-04
                      • 2020-11-05
                      • 2011-05-15
                      • 2013-06-09
                      相关资源
                      最近更新 更多