Home > Web Front-end > CSS Tutorial > How Can I Style Labels Based on Checkbox Status Using Only CSS?

How Can I Style Labels Based on Checkbox Status Using Only CSS?

Mary-Kate Olsen
Release: 2024-12-06 10:12:11
Original
157 people have browsed it

How Can I Style Labels Based on Checkbox Status Using Only CSS?

Styling Labels Based on Checkbox Status Without JavaScript

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 Adjacent Sibling Combinator

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">
Copy after login
Copy after login

Styling the 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;
}
Copy after login
Copy after login

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">
Copy after login
Copy after login
.check-with-label:checked + .label-for-check {
  font-weight: bold;
}
Copy after login
Copy after login

Output:

My Label (bold)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template