Home >Web Front-end >CSS Tutorial >How to Style the Label of a Selected Radio Button in CSS?

How to Style the Label of a Selected Radio Button in CSS?

Barbara Streisand
Barbara StreisandOriginal
2024-12-16 03:53:12907browse

How to Style the Label of a Selected Radio Button in CSS?

How to Style a Selected Radio Button's Label in CSS

Radio buttons provide a unique interaction element in web interfaces, allowing users to select one option from a group. To enhance their visual appeal, it's often desirable to style the label associated with the selected radio button.

The Problem:

You've encountered a challenge while trying to apply styles to the label of a selected radio button using CSS. Your current code snippet includes the following:

.radio-toolbar label + input[type="radio"]:checked { 
    background:pink !important;
}

Identifying the Issue:

This CSS selector doesn't work because the adjacent sibling selector " " matches only the first instance of the element following it. However, in your HTML code, your labels are not immediately adjacent to the input elements.

The Solution:

To style the label of a selected radio button, the CSS selector must specifically target the label element that is associated with the checked input. This can be achieved using the 'for' attribute in the label and 'id' attribute in the respective input element, as demonstrated in the following code:

<div class="radio-toolbar">
  <input type="radio">
.radio-toolbar input[type="radio"] {
  display: none;
}

.radio-toolbar label {
  display: inline-block;
  background-color: #ddd;
  padding: 4px 11px;
  font-family: Arial;
  font-size: 16px;
  cursor: pointer;
}

.radio-toolbar input[type="radio"]:checked+label {
  background-color: #bbb;
}

By adjusting the CSS selector, the code now correctly targets the labels of selected radio buttons and applies the desired styling.

The above is the detailed content of How to Style the Label of a Selected Radio Button in CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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