Reputation: 6087
I felt that the solution for this is easy, but I just couldn't find it on the internet. I need to make a border appear on a radio button and its label if the radio button is selected. The radio button code is for example:
<input type="radio" name="sex" class="sex" value="0">Male</input>
<input type="radio" name="sex" class="sex" value="1">Female</input>
If the male option is selected, the whole radio button and Male label will be enclosed by a rectangle. If the Female radio button then selected, the rectangle from the Male radio button will disappear and change into the Female radio button. But this need to be done only in CSS. No javascript at all. Is this possible? I think the answer might be something to do with pseudoselector, like:
.sex {border: 0}
.sex:checked {border: 1 solid red;}
But this doesn't work. Is there something I've done wrong? Thanks.
Upvotes: 0
Views: 442
Reputation: 586
If you do not mind using jQuery, here is a solution: https://jsfiddle.net/1h5abbnm/
Make sure to add "px" after the 1, as in {border: 1px solid red;}
. It did not work for me until I did.
Similar questions to yours that may help further:
- jquery applying css class on select on radio buttons
- How can I check whether a radio button is selected with JavaScript?
Upvotes: 0
Reputation: 46539
Inputs don't work like that; they don't have content and don't have an end tag. So in your example, the words "Male" and "Female" are not part of the inputs themselves.
The solution is to use <label>
elements where you put the words in, and point those labels to the corresponding inputs with for
attributes.
<input type="radio" name="sex" class="sex" value="0" id="sex0"><label for="sex0">Male</label>
<input type="radio" name="sex" class="sex" value="1" id="sex1"><label for="sex1">Female</label>
And then your css would look something like this:
label {border: 0; padding-left:20px; margin-left:-20px;}
.sex:checked+label {outline: 1px solid red;}
I used an outline rather than a border, to prevent the elements from being reflown when they're clicked.
Note the left padding and negative left margin on the labels, to make it appear that the radio button is in the label. This is necessary, because the radio button itself doesn't respond nicely to a outline
property.
See JSFiddle.
Upvotes: 2