简体   繁体   中英

Set custom image to checkbox without mandatory label

I have a project where sometimes checkboxes don't have labels. The only way of setting custom image for checkbox I've found was setting image for label:before for corresponding label which has for value with id of checkbox.

Are there any CSS way (at least hacky) to set custom image to checkbox without changing markup? input[type="checkbox"]:before works only in Chrome.

The only way I've found that works everywhere except IE for Desktop (even in Edge) is via setting CSS appearance :

 input[type="checkbox"] { width: 16px; height: 16px; -webkit-appearance: none; -moz-appearance: none; appearance: none; background-color: red; } input[type="checkbox"]:checked { background-color: green; } 
 <input type="checkbox" /> 

I think it's impossible to do it without label for all browsers. In my opinion label is necessarily.

But you can use JS for this and one of library like icheck (and many other not only jQuery also pure JS)

Maybe if you add a container to your checkbox like this

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

and then

div{
    position: relative;
    /* Your custom style */
}

input{
    position: absolute;
    height: 100%;
    width: 100%;
    left: 0;
    top: 0;
    opacity: 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM