Home > Web Front-end > CSS Tutorial > Can I Style a Label Based on its Checkbox\'s State Using Only CSS?

Can I Style a Label Based on its Checkbox\'s State Using Only CSS?

Susan Sarandon
Release: 2024-12-01 18:20:10
Original
695 people have browsed it

Can I Style a Label Based on its Checkbox's State Using Only CSS?

Styling Labels Based on Checkbox Status without JavaScript

Question:

Is it possible to modify the styling of a label based on the checked state of its corresponding checkbox without resorting to JavaScript?

Answer:

Yes, it is possible using the adjacent sibling combinator in CSS.

Explanation:

By utilizing the adjacent sibling combinator ( ), you can target elements that immediately follow a specified element. In this case, we use it to style labels (.label-for-check) that are adjacent to checked checkboxes (.check-with-label:checked).

Example:

.check-with-label:checked + .label-for-check {
  font-weight: bold;
}
Copy after login
<div>
  <input type="checkbox" class="check-with-label">
Copy after login

In this example, when the checkbox with the ID "idinput" is checked, the "My Label" label that follows it will become bold. This is because the label meets the following conditions:

  • It is adjacent to a checked checkbox due to the combinator.
  • It matches the .label-for-check class selector.

The above is the detailed content of Can I Style a Label Based on its Checkbox\'s State 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