0

In a div wrapper, I have some radio buttons. When one is selected, I wish to make the label for it have a certain background color. How specific can I be in the CSS rule for this?

HTML:

<div class="switch-wrapper">
    <form>
        <input id="id-1" class="my-switch-on" type="radio" />
        <label for="id-1">Yes</label>
        <input id="id-2" class="my-switch-off" type="radio" />
        <label for="id-2">No</label>
    </form>
</div>

My closest guess:

div.switch-wrapper input[type="radio"].my-switch-on+label {
    background-color: #000;
}

But I can't get it to work. What I did instead was this:

input[type="radio"]:checked + label {
    background: #000;
}

Which certainly work, but I'd like to know how to combine the plus selector with other types of selectors and classes. Is it possible? Can you group selectors with parenthesis? E.g.:

div.foo form.bar + div > span {
    background-color: #000;
}

Which selector has precedence? Can't do more than one?

I mostly do backend engineering so front-end isn't my strong suit. Grateful for any tips or guidelines, links to specs I didn't find an/or short answers. :)

Oscar
  • 714
  • 2
  • 5
  • 22

2 Answers2

2

Being specific in CSS is only important when you are trying to override another rule. Usually it's best to just use something simple like a class.

.my-switch:checked + label {
  background: black;
  color: white;
}
<div class="switch-wrapper">
    <form>
        <input id="id-1" class="my-switch my-switch-on" type="radio" name="onOf" checked />
        <label for="id-1">Yes</label>
        <input id="id-2" class="my-switch my-switch-off" type="radio" name="onOf" />
        <label for="id-2">No</label>
    </form>
</div>
Ori Drori
  • 145,770
  • 24
  • 170
  • 162
  • Not the answer I was looking for ("how to do it", not "should I do it"), but thank you anyway for your input. Yeah I didn't want to do the proposed solution because it wasn't clean, but got interested in what was possible. :) – Oscar Jul 26 '17 at 15:55
  • This MDN article about how [Specificity](https://developer.mozilla.org/en/docs/Web/CSS/Specificity) works might interest you. – Ori Drori Jul 31 '17 at 14:23
1

This SO post should answer your specific question about selector associativity.

If you have control over the HTML and you find yourself needing highly elaborate selectors, it's probably better to slightly reorganize the HTML instead (yes, this goes against the ideal of separating semantics and presentation, but HTML and CSS have always fallen far short in that respect)

Pedro Lopes
  • 48
  • 2
  • 5
  • Thanks! I accepted your answer the linked question contains the actual answer: "Combinators, at least the ones that are currently available, can only express a relationship between exactly two elements", and "...can be solved using the proposed :has() pseudo-class" (still experimental, 2y later...). – Oscar Jul 26 '17 at 15:53