0

I would like to make all labels have color: red; if their sibling input has no value.

I try to select first the inputs without a value like this:

.state-input--red > .input__wrapper > .input__input:not([value])

And after that I'm trying to select his sibling label adding this part:

~ .input__label

So I got this selection and setting color to red, but it doesn't work:

.state-input--red > .input__wrapper > .input__input:not([value]) ~ .input__label {
  color: red;
}

I also tried to specify the sibling selection by adding also the .input__wrapper > before the label, but it doesn't work. Here is my snippet:

.state-input--red > .input__wrapper > .input__input:not([value]) ~ .input__label {
  color: red;
}
<div class="input state-input--red">
  <div class="input__wrapper">
    <label class="input__label" for="input00">I should be black, because my siblin input has a value</label>
    <input id="input00" type="text" value="Hello World">
  </div>
</div>

<hr>

<div class="input state-input--red">
  <div class="input__wrapper">
    <label class="input__label" for="input01">I should be red, because my sibling input has no value</label>
    <input id="input01" class="input__input" type="text">
  </div>
</div>
webta.st.ic
  • 4,781
  • 6
  • 48
  • 98

1 Answers1

1

A selector like a ~ b matches all the siblings b elements preceded by an a element, but in your markup the it's instead the label who precedes the input: that's the reason why it doesn't work.

As a possible solution you could turn your .input__wrapper element into a flexbox container with flex-direction: row-reverse, then switch the order of label and input in the code to keep the current visualization.

Doing so a selector like .input__input:not([value]) ~ .input__label will work as expected.

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
  • So basically, my css selector would work, if the order of the elements in the markup would be reversed? – webta.st.ic Oct 10 '18 at 13:49
  • 1
    @MrBuggy exactly: the general sibling combinator (~) and the adjacent sibling combinator (+) only work for the following sibling/s. – Fabrizio Calderan Oct 10 '18 at 13:51
  • 1
    Or you could use the `order` property to explicitly reorder the visual display of the elements or, with CSS Grid, use named `grid-area`s. – David Thomas Oct 10 '18 at 13:51
  • 1
    Nice on, it works with the flexbox solution, awesome! I though that the (+) selector looks on the order of the elements and the (~) on the adjacent siblings, but no mather wich direction. Thanks for this! – webta.st.ic Oct 10 '18 at 13:53