使用 CSS 隐藏复选框

Hiding checkbox with CSS

我是 html 和 css 的新手,我正在从事一个我想使用自定义复选框的项目。 我试图通过 css 隐藏带有图像的复选框。如果不需要,我不想重写 html。我使用 (display:none; ) 让我的图像覆盖复选框,但这也禁用了我的复选框。有没有办法让我的复选框在不显示的情况下可用?

    input[type='checkbox'] 
    {
    display: none;
    }

    input[type='checkbox'] + label
    {
    background: url('/Pictures/checkbox_unchecked.jpg')no-repeat;
    height: 30px;
    width: 30px;
    background-size: 100%;
    display:inline-block;
    padding: 0 0 0 0px;
    }

    input[type='checkbox']:checked + label
    {
    background: url('Pictures/checkbox_checked.jpg') no-repeat;
    height: 50px;
    width: 200px;
    background-size: 100%;
    display:inline-block;
    padding: 0 0 0 0px;
    }

您可以将复选框的不透明度设置为 0。这仍然使其可点击。

示例(在黑色矩形内单击):

#checkbox {
  opacity: 0;
}
#container {
  border: 2px solid black;
  width: 20px;;
}
<div id="container">
  <input type="checkbox" id="checkbox" onclick="alert('hello')"/>
</div>

label input {
  opacity: 0;
  width: 0;
  height: 0;
  overflow: hidden;
  margin: 0;
  padding: 0;
}

label span.y {
  display: none;
}

label span.n {
  display: inline;
}

label input:checked ~span.y {
  display: inline;
}

label input:checked ~span.n {
  display: none;
}
<label>
  <input type="checkbox" value="1">
  <span class="y">Checked!</span>
  <span class="n">Click me!</span>
</label>

只需将 span.yspan.n. 更改为您的元素(图片或其他内容)即可。

input[type='checkbox'] {
  display: block;
  height: 0;
  width: 0;
  opacity: 0;
  overflow: hidden;
}
input[type='checkbox'] + label {
  background: url('http://lorempixel.com/30/30/') no-repeat;
  height: 30px;
  width: 30px;
  background-size: cover;
  display: inline-block;
}
input[type='checkbox']:checked + label {
  background: url('http://lorempixel.com/50/200/') no-repeat;
  height: 50px;
  width: 200px;
  background-size: cover;
  display: inline-block;
}
<input type="checkbox" id="check" />
<label for="check"></label>