Is it possible to style a label with css based on the input elements "checked" status?

704 Views Asked by At

I have a number of [input type checkbox] with corresponding labels, for example:

<div>
    <input id="idOne" type="checkbox" checked>
    <input id="idTwo"  type="checkbox">
</div>
<div>
    <label for="idTwo">One</label>
    <label for="idTwo">Two</label>
</div>

The label/input are connected with the [for] property. I need to style the lable based on the [checked]-status of the checkbox. Can this be done WITHOUT a combinator as the structure makes using child/sibling combinators a poor choice.

Somthing along the lines of:

label[input:checked = "true"]{
color:pink;
}

Can this be done in a stable fashion with css or will I need to add/remove a classs with JS?

THX in advance :)

I have tried to write a selector that will target the label of a checked input element (type="checkbox").

1

There are 1 best solutions below

1
Shlok Jadeja On

Yes, you can apply CSS to the label on the input checked status.

input[type=checkbox] + label {
    color: #ccc;
    font-style: italic;
} 
input[type=checkbox]:checked + label {
    color: #0964aa;
    font-style: normal;
}
<input type="checkbox" id="idname" name="cb_name"> 
<label for="idname">CSS is Awesome</label>