skip to Main Content

So we have this HTML:

<div>
  <input type="radio" id="a" name="a"><label for="a">aaaa</label>
  <input type="radio" id="b" name="a"><label for="b">bbbb</label>
  <input type="radio" id="c" name="a"><label for="c">cccc</label>
  <input type="radio" id="d" name="a"><label for="d">dddd</label>
</div>

Nothing is checked, so no label is struck. Perfect. If I clicked on a label nothing yet happens. Let’s change that with a bit of CSS:

input:not(:checked) + label {
    text-decoration: line-through;
}

Like this we have the right logic. Alas, the default case is not right. When nothing is checked, all labels are struck! How to change that? Is this possible in CSS only?

I try something cheesy and it went halfway. I can strike every label after. How to the firsts?

input[type="radio"]:checked+label+input+label,
input[type="radio"]:checked+label+input+label+input+label,
input[type="radio"]:checked+label+input+label+input+label+input+label {
  text-decoration: line-through;
}

DEMO

input[type="radio"]:checked+label+input+label,
input[type="radio"]:checked+label+input+label+input+label,
input[type="radio"]:checked+label+input+label+input+label+input+label {
  text-decoration: line-through;
}
<div>
  <input type="radio" id="a" name="a"><label for="a">aaaa</label>
  <input type="radio" id="b" name="a"><label for="b">bbbb</label>
  <input type="radio" id="c" name="a"><label for="c">cccc</label>
  <input type="radio" id="d" name="a"><label for="d">dddd</label>
</div>

Related but not a duplicate of CSS selector for a checked radio button’s label

2

Answers


  1. Chosen as BEST ANSWER

    You can do it with the pseudo-class :has(). Here is the mdn entry about it.

    div:has(> input[type="radio"]:checked)
    > input[type="radio"]:not(:checked)
    + label {}
    

    Or in plain english : we are looking to select a label just next to a radio button who's parent is a div who has at least one radio button child which is checked.

    Demo:

    div:has(> input[type="radio"]:checked) > input[type="radio"]:not(:checked) + label { text-decoration: line-through; }
    <div>
      <input type="radio" id="a" name="a"><label for="a">aaaa</label>
      <input type="radio" id="b" name="a"><label for="b">bbbb</label>
      <input type="radio" id="c" name="a"><label for="c">cccc</label>
      <input type="radio" id="d" name="a"><label for="d">dddd</label>
    </div>


  2. You may combine :has() and :not() + selectors

    div:has(input:checked) :not(input:checked) + label {
      text-decoration: line-through;
    }
    <div>
      <input type="radio" id="a" name="a"><label for="a">aaaa</label>
      <input type="radio" id="b" name="a"><label for="b">bbbb</label>
      <input type="radio" id="c" name="a"><label for="c">cccc</label>
      <input type="radio" id="d" name="a"><label for="d">dddd</label>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search