Simon
Simon

Reputation: 77

Change label color on input focus

I aim to change the label color when its corresponding input has :focus

I am struggling to understand why one works and one does not. Can someone explain what is going on and how to make the non-working example work?

Not working

<form>
  <div class="form-group">
    <label>Why does this not work</label>
    <input name="name" type="text" class="form-control" required>
  </div>
</form>
<style>
form input:focus + label {
  background: rgba(0, 0, 0, 0.5);
  color: red;
  z-index: 2;
  text-transform: uppercase;
}
<style>

Working

<form>
  <div class="form-group">
    <input name="name" type="text" class="form-control" required>
    <label>Why does this not work</label>
  </div>
</form>
<style>
form input:focus + label {
  background: rgba(0, 0, 0, 0.5);
  color: red;
  z-index: 2;
  text-transform: uppercase;
}
<style>

JSFiddle: https://jsfiddle.net/rjaqff2c/

Upvotes: 2

Views: 8036

Answers (2)

BeNdErR
BeNdErR

Reputation: 17929

+ is used to target the element immediately after the element preceding the plus sign.

In your case

form input:focus + label

selects the label after the input, and not the preceding one (if present)

Find more info here

Upvotes: 1

dowomenfart
dowomenfart

Reputation: 2803

The + in CSS selects elements that are placed immediately after the element. Read more about selectors here

Upvotes: 1

Related Questions