Sung Sung - 2 months ago 9
CSS Question

CSS selector issue with highlighting checkbox

When I put the label after checkbox, this CSS selector works.

input[type=checkbox]:checked + label {
color: red;
}

<input type="checkbox"><label>Checkbox1</label>


But I'd like to make the checkbox to be checked when the label is clicked on as well.

enter image description here

Here is the CSS for the updated HTML.

label > input[type=checkbox]:checked {
color: red;
}

<label><input type="checkbox">Checkbox1</label>


What could I be doing wrong here?

Here is the simplified HTML and style in one file.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Selectors Test Ground</title>

<style>
label > input[type=checkbox]:checked {
color: red;
}
</style>
</head>
<body>
<form id="checkBoxForm">
<ul>
<li>
<label><input type="checkbox">Checkbox1</label>
</li>
<li>
<label><input type="checkbox">Checkbox2</label>
</li>
<li>
<label><input type="checkbox">Checkbox3</label>
</li>
</ul>
</form>
</body>

Answer

You must use "for" attribute to set checkbox checked when click on label, it's not a selector, it's HTML attribute and points to an id, see the example below: (i only modified first one).

EDITED: Added css on snippet (and deleted style tags and content copied from the question)

input[type=checkbox]:checked + label {
        color: red;
    }
    <form id="checkBoxForm">
        <ul>
            <li>
                <input id="chk1" type="checkbox"><label for="chk1">Checkbox1</label>
            </li>
            <li>
                <label><input type="checkbox">Checkbox2</label>
            </li>
            <li>
                <label><input type="checkbox">Checkbox3</label>
            </li>
        </ul>
    </form>

And you must not set an imput into a label.

Comments