2

Consider the following HTML structure:

<input type=radio name=picker value=foo> <input type=radio name=picker value=bar> etc
<ul>
    <li class=foo>Foo #1</li>
    <li class=bar>Bar #1</li>
    <li class=foo>Foo #2</li>
    <li class=bar>Bar #2</li>
</ul>

I want to style those list items which match the currently-selected radio button. This works if all the possible radio button values are hard-coded:

input:checked[value=foo] ~ ul li[class~=foo] {
    background: blue;
    color: white;
}

input:checked[value=bar] ~ ul li[class~=bar] {
    background: blue;
    color: white;
}

Is there any way to say "input:checked" and then "li[class~=[the value of the currently-selected input]]" ? Assume that the radio buttons and list items are all dynamically generated.

If all else fails, I can dynamically generate the CSS too, but that seems unideal.

rosuav
  • 466
  • 4
  • 12
  • 1
    Did you try that https://stackoverflow.com/questions/1431726/css-selector-for-a-checked-radio-buttons-label – Awais Dec 02 '19 at 13:28
  • @Awais Yes, this is more than can be done with simple sibling selectors. – rosuav Dec 02 '19 at 13:34
  • Did that solve your problem – Awais Dec 02 '19 at 13:35
  • 1
    you cannot do this with CSS – Temani Afif Dec 02 '19 at 13:36
  • if next sibling selector won't solve your problem (as in that link in the first comment) you should try with javascript – Ivana Bakija Dec 02 '19 at 13:37
  • As you can see, I've already made use of the sibling selector in the code in the question. What I want to do is reference the value from the parent in the selector for the child. No, @Awais, the simple example in that link did not solve my problem. – rosuav Dec 02 '19 at 13:45
  • _What I want to do is reference the value from the parent in the selector for the child_ Since there is not a parent selector in CSS, nor a way to do this with CSS, you need to use JavaScript. – disinfor Dec 02 '19 at 13:48
  • I'm not asking for a parent selector. I'm asking for a way to retain a value from one part of a selector to another - something like a backreference in a regex. – rosuav Dec 02 '19 at 13:58
  • Simply, no @rosuav you can kind of hack it using `:target` but it would require maintenance / js possibly and it's not really accessible friendly as it changes how pages navigate. It would just be easier to use javascript with the original element – soulshined Dec 02 '19 at 16:21

1 Answers1

1

This seems to be a fundamental limitation of CSS (as of 2019 - if this changes in the future, someone can post a different answer). Since the input controls have to be script-generated anyway, it's simplest to script-generate the CSS as well.

rosuav
  • 466
  • 4
  • 12