CSS: how to select the text adjacent to a checkbox

CSS: how to select the text adjacent to a checkbox

CSS allows us to select the text adjacent to a checkbox.

CSS allows us to select the text adjacent to a checkbox.

We have the following HTML structure.


<form action="" method="get">
    <div>
        <input type="checkbox" class="checkbox" name="test" value="1">
        <span>Checkbox checked!</span>
    </div>
</form>

We can use the :checked pseudo-class matching a checkbox when it's activated. Then we can select the next sibling element that contains our text.


.checkbox {
    margin-right: 4px;
}

.checkbox + span {
    transition: background-color 400ms ease-in;
}

.checkbox:checked + span {
    background-color: #ffaa57;
}

You can see the above code in action on the following page.