-1

I think my code is correct, but label color does not change when input on focus. Please let me know why so.

https://jsfiddle.net/wvs34qhu/

body {
  font-family: sans-serif;
}
.field {
  position: relative;
  max-width: 250px;
}
label {
  box-sizing: border-box;
  display: block;
  font-size: .8125em;
  padding: .75em 12px;
  pointer-events: none;
  position: absolute;
  text-overflow: ellipsis;
  top: 0;
  text-align: left;

  user-select: none;
  white-space: nowrap;
  width: 100%;
  z-index: 1;
}
input {
  background-color: #f5f5f5;
  border:0;
  border-bottom:2px solid grey;
  font-size: 1.3125em;
  outline:0;
  padding-top:24px;
  padding-left:12px;
  padding-bottom:2px;
  width: 100%;
  
}

input:focus + label{
  color:red;
}

input:focus {
   border-bottom:2px solid red;
}
<div class="field">
  <label for="input-name">Email address</label>
  <input id="input-name" type="name" />
</div>

Thanks in advance!

Martin
  • 16,093
  • 1
  • 29
  • 48
01e5Dk
  • 390
  • 1
  • 2
  • 14

1 Answers1

2

The reason that this isn't currently working is to do with your CSS selector:

input:focus + label

This explicitly states that in the HTML, the label is directly after the input (which it is not).

To get it working, as you have absolutely positioned your label you can switch these around in your HTML:

<div class="field">
  <input id="input-name" type="name" />
  <label for="input-name">Email address</label>
</div>

The selector will now work as expected. See the below snippet:

body {
  font-family: sans-serif;
}
.field {
  position: relative;
  max-width: 250px;
}
label {
  box-sizing: border-box;
  display: block;
  font-size: .8125em;
  padding: .75em 12px;
  pointer-events: none;
  position: absolute;
  text-overflow: ellipsis;
  top: 0;
  text-align: left;

  user-select: none;
  white-space: nowrap;
  width: 100%;
  z-index: 1;
}
input {
  background-color: #f5f5f5;
  border:0;
  border-bottom:2px solid grey;
  font-size: 1.3125em;
  outline:0;
  padding-top:24px;
  padding-left:12px;
  padding-bottom:2px;
  width: 100%;
  
}

input:focus + label{
  color:red;
}

input:focus {
   border-bottom:2px solid red;
}
<div class="field">
  <input id="input-name" type="name" />
  <label for="input-name">Email address</label>
</div>
Martin
  • 16,093
  • 1
  • 29
  • 48