css - 如何将图像添加到自定义复选框的背面

标签 css checkbox slider label

我在 codepen 上发现了一个看起来非常干净的自定义复选框,并且刚刚更新了一个元素来使用它。现在我的表单的不同部分的背景颜色不同,但我只想让背景成为一个图标,而不仅仅是纯色

注释掉的东西不起作用

.label-switch {
  display: inline-block;
  position: relative;
}

.label-switch::before,
.label-switch::after {
  content: "";
  display: inline-block;
  cursor: pointer;
  transition: all 0.5s;
}

.label-switch::before {
  width: 3em;
  height: 1em;
  border: 1px solid #757575;
  border-radius: 4em;
  background: #888888;
}

.label-switch::after {
  position: absolute;
  left: 0;
  top: -20%;
  width: 1.5em;
  height: 1.5em;
  border: 1px solid #757575;
  border-radius: 4em;
  background: #ffffff;
}

.input-switch:checked~.label-switch::before {
  background: #00a900;
  border-color: #008e00;
}

.input-switch:checked~.label-switch::after {
  left: unset;
  right: 0;
  background: #00ce00;
  /*background-image:(url(http://pngimg.com/uploads/pokeball/pokeball_PNG8.png);*/
  /*background: url(http://pngimg.com/uploads/pokeball/pokeball_PNG8.png);*/
  border-color: #009a00;
}
<input class='input-switch' type="checkbox" id="demo" />
<label class="label-switch" for="demo"></label>
<span class="info-text"></span>

最佳答案

您所做的一切都是正确的,只是背景图像需要设置 background-positionbackground-size 如果您在我的代码片段中切换复选框,您应该会看到背景图案,如您所愿。

.label-switch{
    display: inline-block;
    position: relative;
 }

.label-switch::before, .label-switch::after{
     content: "";
     display: inline-block;
     cursor: pointer;
     transition: all 0.5s;
}

.label-switch::before {
     width: 3em;
height: 1em;
border: 1px solid #757575;
border-radius: 4em;
background: #888888;
}

.label-switch::after {
     position: absolute;
    left: 0;
    top: -20%;
    width: 1.5em;
    height: 1.5em;
    border: 1px solid #757575;
    border-radius: 4em;
    background: #ffffff;
}

.input-switch:checked ~ .label-switch::before {
    background: #00a900;
    border-color: #008e00;
}

.input-switch:checked ~ .label-switch::after {
    left: unset;
    right: 0;
    background: #00ce00;
    background-image:url(http://pngimg.com/uploads/pokeball/pokeball_PNG8.png);
    background-size:contain;
    background-position:center;
    border-color: #009a00;
}
<input class='input-switch' type="checkbox" id="demo"/>
<label class="label-switch" for="demo"></label>
<span class="info-text"></span>

关于css - 如何将图像添加到自定义复选框的背面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57419757/

相关文章:

css - 使流体大小的 block 粘在顶 Angular 并允许内容在其周围流动,但在某些断点处保持在内容下方。

javascript - 如果使用 jQuery 选择了一个选项,则更改 CSS 属性

javascript - 听取下拉菜单中的值变化?

jQuery ui slider 值错误?

jquery - 加载 slider 后删除背景加载 gif

javascript - 在调整窗口大小时移动 div 时需要帮助

javascript - PHP/HTML/CSS : links not clickable

c# - 只能选中一个复选框

c# - 将复选框的值传递给 asp.net mvc4 中的 Controller 操作

angularjs 切换全选和取消选择