0

Curious if I did miss something or it is really not possible select next label for the following html chunk:

<div class="col-md-1">
  <input type="radio" name="name" value="alice" id="name-alice">
</div>
<label for="name-alice">Alice</label>
<div class="col-md-1">
  <input type="radio" name="name" value="bob" id="name-bob">
</div>
<label for="name-bob">Bob</label>

I'd like to select label for checked input, something like

input:checked + label {
    background-color: red;
}

The + CSS selector obviously does not work here. Any idea how to get work around this ?

rationale: Generally it may be considered a "parent selector issue", but input & label elements are specific as being paired with for and id attributes and was unclear if there is some counterpart in CSS.

joanbm
  • 643
  • 4
  • 12
  • 4
    Can your markup be changed. With current HTML, you can't select the `label` based on `input`. – Harry Aug 15 '15 at 08:15
  • also consider using jQuery if you're flexible with it. – Nikunj Madhogaria Aug 15 '15 at 08:20
  • @Harry Why not ? `for` attribute assigns `label` to `input` by its `id` – joanbm Aug 15 '15 at 08:30
  • 5
    @JoanBlackmoore: I can't explain why CSS selectors work the way they have been designed to. We have to ask those who wrote the specs but in CSS there is currently no way to do what you want without changing the markup. And, I don't think the working of the `for` has anything to do with CSS. – Harry Aug 15 '15 at 08:32
  • 2
    possible duplicate of [Is there a CSS parent selector?](http://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector) – sergdenisov Aug 15 '15 at 10:25

1 Answers1

2

Move label inside div:

<div class="col-md-1">
  <input type="radio" name="name" value="bob" id="name-bob">
  <label for="name-bob">Bob</label>
</div>
deniskoronets
  • 490
  • 3
  • 15
  • Thanks, but that's not proper solution as only `input` need to be formatted by `col-md-1` class, not `label`. – joanbm Aug 15 '15 at 08:32
  • 2
    @JoanBlackmoore that's the only solution available without resorting to JS. Simply put, CSS does not have parent selectors. If the formatting of the label is so important, couldn't you just assign a class to the label and counter the styles imposed by `.col-md-1`? – zer00ne Aug 15 '15 at 11:05