如何改变复选框按钮的外观?

4

我需要更改复选框按钮的外观,确切地说,我需要将自定义背景图像放置在常规灰色正方形的位置。

现在我尝试了以下代码:

[type="checkbox"] {
  width: 15px;
  height: 15px;
  background-image: url("../images/checkbox.png")
}

[type="checkbox"]:checked {
  width: 15px;
  height: 15px;
  -webkit-appearance: none;
  background-image: url("../images/checkbox-c.png")
}

当复选框被选中时,它能够正常工作,但是当处于空闲状态时,它无法将背景图像更改为checkbox.png,而仍然保持简单的灰色正方形。


2
可能是重复的问题:如何使用CSS样式化复选框? - Saif
有一些网站可以帮助你完成这个任务,例如:http://www.csscheckbox.com/。 - Victor
2个回答

4

通常有许多方法来实现它,这些方法通常包括在:checked状态下对紧随其后的元素进行样式设置、隐藏复选框,并利用label的本地行为来包装结果。

label {
  position: relative; /* <-- usually handy to have for styling */
}
label input {
  display: none; /* <-- hide the default checkbox */
}
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: blue;
}
<label>
  <input type='checkbox'><span></span> Checkbox label</label>


2

我不知道为什么其他答案被删除了,但是以下方法很可能适用,因为它在我这里有效:

[type="checkbox"] {
    width: 26px;
    height: 26px;
    -webkit-appearance: none; /*<----this needs to be added here.*/
    background-image: url("https://cdn1.iconfinder.com/data/icons/windows8_icons_iconpharm/26/unchecked_checkbox.png")
}
[type="checkbox"]:checked {
    width: 26px;
    height: 26px;
    -webkit-appearance: none;
    background-image: url("https://cdn1.iconfinder.com/data/icons/windows8_icons_iconpharm/26/checked_checkbox.png")
}
<input type="checkbox" />


我删除了我的回答,因为问题提出者说它对他没有起作用,而我相信了他。 - Danield
我也不是,我没有删除它。它运行得很好,谢谢 :) - Vladimir Jovanovic
1
很高兴这能帮到你,@VladimirJovanovic。 - Jai
Danield 我试过了,但没有起作用,现在我试了 Jai 的,不知何故它可以工作 lol - Vladimir Jovanovic
@Danield,实际上您已经删除了您的答案,而我正在您的评论区发布一个js fiddle,但是由于帖子已被删除,所以我无法发布。因此,我添加了这个带有片段的答案。 - Jai
没问题。谢谢你的支持。 - Danield

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接