Problem of choosing CSS selector with highlight

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

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

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

But I want the checkbox to be checked when the label is clicked.

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 can i do wrong here?

Here is 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>
+4
source share
2 answers

You must use the “for” attribute to set the checkbox marked when clicking on the label, this is not a selector, its HTML attribute also indicates an identifier, see the example below: (I just changed the first).

EDITED: Added css in snippet (and style tags and content copied with the question removed)

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>
Run code

And you should not set imput in the label.

+4

.

<input type="checkbox">
<label>Checkbox Label</label>

. , , , .

<label>
    <input type="checkbox">
    Checkbox Label
</label>

, , . , , CSS , .

- HTML.

<input type="checkbox" id="1">
<label for="1">Checkbox Label</label>
0

Source: https://habr.com/ru/post/1655757/


All Articles