0

I have this form and I can't select the sibling "label" to style it. However, when I put the "label" under the "input" it works. I want to style it as it is to be easy to control its style. here is a link: https://jsfiddle.net/grucdymb/18/

<form action="">

  <div class="box">
    <input type="email" name="email" id="email" 
placeholder="example@email.com" autocomplete="off" required>
    <label for="email"> This is working </label>
  </div>

  <div class="box">
    <label for="subject"> This is not working </label>
    <input type="text" name="subject" id="subject" placeholder="Subject" 
autocomplete="off" required>
  </div>
</form>
Momo
  • 59
  • 1
  • 5
  • 2
    *The general sibling combinator (~) separates two selectors and matches the second element **only if it follows the first element*** - https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_combinator – BenM Sep 10 '19 at 13:19
  • 1
    This answer here expands on what Ben stated above: https://stackoverflow.com/questions/10782054/what-does-the-tilde-squiggle-twiddle-css-selector-mean – elke_wtf Sep 10 '19 at 13:21
  • Why don't you style by using nth-of-type on the div? So example:- .box:nth-of-type(2) label {color:red;} – Brad Sep 10 '19 at 13:23
  • 1
    @Brad they want to style the label depending on the :focus state of the input. – misorude Sep 10 '19 at 13:29
  • Thank you all. I made it with jQuery, it is easier. – Momo Sep 10 '19 at 14:33

1 Answers1

1

It will not apply for the later example, because the label does not follow the input element.

From MDN:

The general sibling combinator (~) separates two selectors and matches the second element only if it follows the first element (though not necessarily immediately), and both are children of the same parent element.

Of special note is this part in particular:

...matches the second element only if it follows the first element...

BenM
  • 52,573
  • 26
  • 113
  • 168