frontMan86
frontMan86

Reputation: 33

toggling styles on label when input field is focus with css only

I need to toggle styles on the corresponding label when input's focus. HTML+CSS:

<div>
<label for="e_mail">E-Mail</label>
<input type="text" />
</div>
input[type=text]:focus + label {
color: red;
}

P.S. how to do this without changing tags "label" and "input" in HTML?

Upvotes: 1

Views: 983

Answers (1)

Jacob
Jacob

Reputation: 2071

You can only do that with pure CSS if label is inserted after the input. A fix to that could be using float: left; on the label to put it to the left.

Also, <label for=""></label> require the input to have a id in order to work propertly.

<div>
  <input type="text" id="e_mail" />
  <label for="e_mail">E-Mail</label>
</div>

-

input[type="text"]:focus + label {
  color: red;
}
label {
  float: left;
}

https://jsfiddle.net/vcw880fr/1/

Upvotes: 1

Related Questions