0

I have checkboxes and radio buttons. I want what is selected (checked) to be bold.

I use "label for" in html, as advised here: CSS selector for a checked radio button's label

In my case my radiobutton options can be disabled (depending on other fields of the form), and if disabled I don't want them to be bold.

I see how to do this in javascript, but I am trying to find a way in CSS.

Code built from the link:

:checked + label {
  font-weight: bold;
}
<input id="rad1" type="checkbox" name="rad" checked/><label for="rad1">Radio 1</label>
<input id="rad2" type="checkbox" name="rad"/><label for="rad2">Radio 2</label>
<input id="chkdis1" type="radio" name="chkdis" value="chkdis1" checked disabled><label for="chkdis1"> chkdis</label>
<input id="chkdis2" type="radio" name="chkdis" value="chkdis2" disabled><label for="chkdis2"> chkdis</label>

My solution in CSS:

:checked + label {
  font-weight: bold;
}

:disabled + label {
  font-weight: normal;
}
<input id="rad1" type="checkbox" name="rad" checked/><label for="rad1">Radio 1</label>
<input id="rad2" type="checkbox" name="rad"/><label for="rad2">Radio 2</label>
<input id="chkdis1" type="radio" name="chkdis" value="chkdis1" checked disabled><label for="chkdis1"> chkdis</label>
<input id="chkdis2" type="radio" name="chkdis" value="chkdis2" disabled><label for="chkdis2"> chkdis</label>

What I don't like about my solution: if I put :disabled + label before :checked + label, it won't work anymore. It's only a matter of time before someone inverts both in the code and kills the expected behavior :-)

Any better idea?

Pierre
  • 145
  • 1
  • 15

2 Answers2

2

Try using :not()

:not(:checked)+label,
:checked:disabled+label {
  font-weight: normal;
}

:checked+label {
  font-weight: bold;
}
<input id="rad1" type="checkbox" name="rad" checked/><label for="rad1">Radio 1</label>
<input id="rad2" type="checkbox" name="rad" /><label for="rad2">Radio 2</label>
<input id="chkdis1" type="radio" name="chkdis" value="chkdis1" checked disabled><label for="chkdis1"> chkdis</label>
<input id="chkdis2" type="radio" name="chkdis" value="chkdis2" disabled><label for="chkdis2"> chkdis</label>
Paulie_D
  • 107,962
  • 13
  • 142
  • 161
1

just add a class to your label. Although you do know what the 'C' stands for in CSS, right?

:disabled + label {
  font-weight: normal;
}

:checked + .xyz{
  font-weight: bold;
}
<input id="rad1"  type="checkbox" name="rad" checked/><label class='xyz' for="rad1">Radio 1</label>
<input id="rad2"  type="checkbox" name="rad"/><label class='xyz' for="rad2">Radio 2</label>
<input id="chkdis1" type="radio" name="chkdis" value="chkdis1" checked disabled><label for="chkdis1"> chkdis</label>
<input id="chkdis2" type="radio" name="chkdis" value="chkdis2" disabled><label for="chkdis2"> chkdis</label>
DCR
  • 14,737
  • 12
  • 52
  • 115