Change checkbox label css property with checkbox checked

后端 未结 2 1357
-上瘾入骨i
-上瘾入骨i 2020-12-17 00:14

I have the following html:

  


        
相关标签:
2条回答
  • 2020-12-17 00:58

    You can achieve this with pure css like so,

    <input type="checkbox" id="cb_1" value="cb_val" name="cb_name">
    <label for="cb_1">
         my checkbox text
    </label>
    

    With this css,

    label { background-color:#333; color:#FFF; }
    
    input[type="checkbox"]:checked + label {
        background: brown;
    }
    

    JSFIDDLE

    Keep in mind

    The label has to be after the checkbox so you will need to style it around more to keep the same look you had.

    Here is an option of styling it more to have the same appearance as you wanted, New fiddle. THIS DOES NOT involve positioning anything absolute, just some trickery.

    0 讨论(0)
  • 2020-12-17 01:09

    You can't style the label itself directly via only CSS when the label is checked, but you can style a sibling of the checkbox.

    http://jsfiddle.net/QdDpL/

    HTML

    <label>
        <input class="check" type="checkbox" />
        <span class="label-text">Checkbox</span>
    </label>
    

    CSS

    label {
        background: yellow;
    }
    label .label-text {
        background: cyan;
    }
    label input.check:checked + .label-text {
        background: lime;
    }
    

    You may also be able to fiddle with floats and padding to make the checkbox appear as if it was inside the .label-text span.

    See the following links for browser support on the sibling selector: http://caniuse.com/css-sel2

    Alternately as another answer said, you can style the label if it is a sibling of the checkbox - but then just like my answer still would not contain the checkbox in the label.

    0 讨论(0)
提交回复
热议问题