简体   繁体   中英

CSS - Label/Checkbox Image replacement

I have the following CSS:-

#profile-container ul label:before {
    content: "";
    display: inline-block;
    width: 33px;
    height: 33px;
    margin-right: 10px;
    position: relative;
    left: 0;
    top: 10px;
    background: url(../img/c-unchecked.png);
}

#profile-container input:checked label:before {
    background: url(../img/c-checked.png);  
}

With the following markup:-

<ul class="acf-checkbox-list checkbox vertical">
    <li><label><input id="acf-field-interested_in" type="checkbox" class="checkbox" name="interested_in" value="permanent" checked="yes">Permanent</label></li>
    <li><label><input id="acf-field-interested_in-Temporary" type="checkbox" class="checkbox" name="interested_in" value="Temporary" checked="yes">Temporary</label></li>
    <li><label><input id="acf-field-interested_in-Interim" type="checkbox" class="checkbox" name="interested_in" value="Interim" checked="yes">Interim</label></li>
</ul>

I can't see why the image isn't being replaced once you click on the checkbox, any ideas?

You need to pay attention to the nesting selectors:

#profile-container input:checked label:before {

label is not inside input . It's the parent of input , and sadly CSS has no parent selector. You can restructure your code to:

<li><input /><label></label></li>

Then use the sibling selector:

#profile-container input:checked+label:before {

The problem comes from trying to target the parent selector label:before with input:checked . CSS doesn't allow you to 'climb up the DOM' in this manner. Instead you may want to try with the following markup :

<ul class="acf-checkbox-list checkbox vertical">
    <li><input id="acf-field-interested_in" type="checkbox" class="checkbox" name="interested_in" value="permanent" checked="yes"/><label>Permanent</label></li>
    <li><input id="acf-field-interested_in-Temporary" type="checkbox" class="checkbox" name="interested_in" value="Temporary" checked="yes"/><label>Temporary</label></li>
    <li><input id="acf-field-interested_in-Interim" type="checkbox" class="checkbox" name="interested_in" value="Interim" checked="yes"/><label>Interim</label></li>
</ul>

Don't forget to close your input tags as per the HTML specs!

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