Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a background-image for checkbox

Tags:

html

css

checkbox

I'm trying to setup some checkboxes so that when not checked they use one image that I've got and then when checked they used another image. Here's my current checkboxes:

<input type="checkbox" name="fordCheckBox" value="Ford">

I'm also using the following CSS in order to set the background image for each checkbox.

input[type=checkbox][name=fordCheckBox] {
        background:url("https://pbs.twimg.com/profile_images/550291079719698432/LbybHjIh.jpeg") no-repeat;
        height: 25px;
        width: 25px;
        background-size: 50%;
    }

    input[type=checkbox][name=fordCheckBox]:checked {
        background:url("http://contentservice.mc.reyrey.net/image_v1.0.0/2267461") no-repeat;
        height: 25px;
        width: 25px;
        background-size: 50%;
    }

As you can see in my JSFiddle example the icons is the correct size but it's never setting the background image like it should be. Any suggestions?

like image 403
pallasmedia Avatar asked Jun 02 '16 04:06

pallasmedia


People also ask

How do I put an image in a checkbox in HTML?

The solution is to use the :checked css selector. What we want to achieve is when you click the label (which will be an image or an icon) the input field will change to "checked" and the label image will change to something different.

How do you put a background color in a checkbox?

You can use accent-color property in css to change background color of both checkbox and radio buttons.

How can I display the checkbox over the images for selection?

This can be done with pure CSS, assuming you have fixed width and height for all images. The trick is setting absolute position for the checkbox then assign bottom and right to zero. Live test case. As for click events, just apply click handler to each checkbox and it will work just fine.. see in this updated fiddle.


1 Answers

You can just do it with label

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

input[type=checkbox] + label {
    display:inline-block;
    padding: 0 0 0 0px;
    background:url("https://pbs.twimg.com/profile_images/550291079719698432/LbybHjIh.jpeg") no-repeat;
    height: 125px;
    width: 125px;;
    background-size: 50%;
}

input[type=checkbox]:checked + label {
    background:url("http://contentservice.mc.reyrey.net/image_v1.0.0/2267461") no-repeat;
    height: 125px;
    width: 125px;
    display:inline-block;
    background-size: 50%;
}

Html

<input type="checkbox" name="fordCheckBox" id="Ford" value="Ford">
<label for="Ford"></label>

Please check updated jsfiddle https://jsfiddle.net/s4nr6q3d/

like image 63
Malith Avatar answered Nov 15 '22 17:11

Malith