如何在复选框上应用背景图像

时间:2015-12-31 14:44:07

标签: css

如何在复选框上应用背景图像。我知道这很容易,但我发现它很难 这是我的HTML代码。我不知道这个

中的问题是什么
    <div>
<style>
input[type="checkbox"], input[type="radio"] {
    box-sizing: border-box;
    padding: 0px;
    background: transparent url("http://ilexsquare.com/finalhot/wp-content/uploads/2015/12/hotlogo-2.png") repeat scroll 0% 0%;
}
</style>
<input type="checkbox" />
</div>

请帮助

3 个答案:

答案 0 :(得分:0)

Julian Be是正确的,您无法直接将背景图像应用于复选框。

实现这一目标的唯一方法是欺骗结果。您可以通过将<label>包围在其overflow设置为hidden的复选框中,然后将复选框本身移至溢出来实现此目的。这样可以确保复选框仍然可以点击,但对用户不可见。然后,您可以在复选框后添加<span>,并使用:checked选择器和+选择器根据复选框的状态将背景图像应用于此元素。

像这样的东西            

  /* Set overflow of label to hidden so the checkbox can disappear */
  .label-with-hidden-checkbox {
    overflow: hidden;
    position: relative;
  }

  /* Move the checkbox out of view */
  .label-with-hidden-checkbox .hidden-checkbox {
    position: absolute;
    left: -9999px;
  }

  /* Set the background image of the spoof checkbox to the unchecked state */
  .label-with-hidden-checkbox .hidden-checkbox + .spoof-checkbox{
    display: inline-block;
    margin-right: 10px;
    background: transparent url("unchecked-state-image.png") repeat scroll 0% 0%;
  }

  /* When the checkbox is checked set the background image of the spoof checkbox to the checked state */
  .label-with-hidden-checkbox .hidden-checkbox:checked + .spoof-checkbox{
    display: inline-block;
    width: 20px;
    height: 20px;
    margin-right: 10px;
    background: transparent url("checked-state-image.png") repeat scroll 0% 0%;
  }

  </style>
  <label class="label-with-hidden-checkbox">
    <input class="hidden-checkbox" type="checkbox" /><span class="spoof-checkbox"></span> This is a checkbox
  </label>
</div>

希望有所帮助。

答案 1 :(得分:0)

您可以使用标签在此处应用图像是jsfiddle

jsfiddle 这是您的HTML代码:

    <input type="checkbox" />
<label></label>

和CSS:

input[type="checkbox"], input[type="radio"] {
box-sizing: border-box;
padding: 0px;
opacity: 0;
cursor: pointer;
}
label{
  height:100px;
  width:100px;
}
label:before{
  content:"";
width: 100px;
height: 60px;
display: block;
z-index: 1;
border-radius: 2.5px;
background:  url("http://ilexsquare.com/finalhot/wp-content/uploads/2015/12/hotlogo-2.png") repeat scroll 0% 0%;
}

答案 2 :(得分:-1)

您无法将图像添加到复选框。

相关问题