2

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/

Simon
  • 77
  • 1
  • 2
  • 8
  • 1
    Label is above input in first example so `+` can't target it. There is no previous sibling selector that could work for this markup. – emmanuel Mar 25 '15 at 12:59
  • Have a look at: http://www.w3.org/TR/CSS2/selector.html#adjacent-selectors – Hashem Qolami Mar 25 '15 at 13:02
  • 1
    possible duplicate of [Is there a previous sibling selector?](http://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-selector) – Paulie_D Mar 25 '15 at 13:10

2 Answers2

1

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

dowomenfart
  • 2,803
  • 2
  • 15
  • 17
1

+ 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

BeNdErR
  • 17,471
  • 21
  • 72
  • 103
  • Then why does 'form label + input:focus' not work to change the color of the label? https://jsfiddle.net/rjaqff2c/1/ – Simon Mar 25 '15 at 13:03
  • because you are saying "for each form find its childs then for all the labels find the siblings input with focus and apply the css style". The style is applied to the input,not to the label – BeNdErR Mar 25 '15 at 13:05
  • would I have to give each form an ID to do this? - could you show me a working example? – Simon Mar 25 '15 at 13:06
  • Yes you could set an id for each form but I think it would be ugly and hard to maintain if the number of forms grows. If you could use js to manage the label css I think it would be far better – BeNdErR Mar 25 '15 at 13:09
  • have a look here http://stackoverflow.com/questions/967096/using-jquery-to-test-if-an-input-has-focus – BeNdErR Mar 25 '15 at 13:36