Many scenarios in web development involve displaying information based on user input. One common example is toggling the appearance of a label when its corresponding checkbox is checked or unchecked. While JavaScript provides a straightforward way to achieve this, this article explores a pure CSS solution.
The key to this technique lies in the adjacent sibling combinator ( ). This selector allows you to target elements that are adjacent to and preceded by another element within the logical DOM tree. In our case, we want to target the label element that comes immediately after the checkbox.
Consider the following HTML structure:
<div> <input type="checkbox" class="check-with-label">
Now, using the adjacent sibling combinator, we can write CSS rules that target the label element only when its preceding checkbox is checked:
.check-with-label:checked + .label-for-check { font-weight: bold; }
This rule states that any element with the class "check-with-label" that is in a checked state will have its adjacent sibling element with the class "label-for-check" styled with bold font weight.
Example:
Applying these CSS rules to the given HTML example will result in something like this:
<div> <input type="checkbox" class="check-with-label">
.check-with-label:checked + .label-for-check { font-weight: bold; }
Output:
My Label (bold)
In this case, "My Label" will be displayed in bold because the preceding checkbox is checked, indicating that this pure CSS technique successfully changes the label's appearance based on the checkbox status.
The above is the detailed content of How Can I Style Labels Based on Checkbox Status Using Only CSS?. For more information, please follow other related articles on the PHP Chinese website!