Home >Web Front-end >CSS Tutorial >How to Correctly Style Selected Radio Button Labels in CSS?
In this example, we aim to style the labels of selected radio buttons. However, the provided CSS doesn't seem to work as intended. Let's analyze the HTML and CSS code to identify the issue.
The HTML code contains a div with the class "radio-toolbar" that holds the radio buttons and their labels. Each radio button is hidden using display: none;. The labels have styles applied to them, including a background color, border, and padding.
Moving on to the CSS, the first rule hides the radio button inputs, which is correct. The second rule styles the labels themselves. The issue lies in the third rule, which is intended to style the label of the selected radio button.
In the third rule, we are trying to select the label element immediately adjacent to a checked radio button using the following selector: .radio-toolbar label input[type="radio"]:checked. However, the selector matches only the immediately preceding element. In this case, it expects the radio button input to come before the label, but in the HTML code, the label comes before the input.
To fix the issue, we can use the following CSS instead:
By changing the selector to .radio-toolbar input[type="radio"]:checked label, we ensure that the background color is applied to the label that follows the checked radio button input.
Apart from the selector issue, there are a few other changes we can make for better functionality:
Here's the updated HTML and CSS:
HTML:
CSS:
With these changes, the radio button labels will now be properly styled and functional, indicating the selected option with the pink background color.
The above is the detailed content of How to Correctly Style Selected Radio Button Labels in CSS?. For more information, please follow other related articles on the PHP Chinese website!