0

How can I style a label element that precedes an input when I focus on the input element?

Take the following code:

label {
  background: red;
}

input[type="text"]:focus ~ label {
  background: blue;
}
<div>
  <label>Hello World</label>
  <input type="text">
</div>

On focus of the input I want to change the style of the preceding label element using the general sibling selector ('~'). What am I doing wrong?

Joel Hoelting
  • 1,862
  • 2
  • 23
  • 45
  • On a side note, your label should have a `for` attribute with the value of the ID that it is a label for, or it should wrap said element. – j08691 Dec 06 '18 at 19:12
  • If the label is a general sibling of the input then why isn't it being selected? – Joel Hoelting Dec 06 '18 at 19:19
  • The general sibling selector only selects the following sibling. "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." [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_combinator) – j08691 Dec 06 '18 at 19:20
  • I was using this resource: https://www.w3schools.com/css/css_combinators.asp The description of 'general sibling combinator' was way too ambiguous. – Joel Hoelting Dec 06 '18 at 19:29
  • Yeah you'll find most people here frown on w3schools. You're better off with MDN. – j08691 Dec 06 '18 at 19:36

0 Answers0