4

I want to move a label above an input box when a user focuses on the input box. There is an answer here, however, there are some differences. I can't use required as I am using custom validations. Also, there is more than one input box.

See my code below. I must be missing something silly.

.field {
  position: relative;
  padding-top: 10px;
}

.form label {
  position: absolute;
  top: 8px;
  left: 10px;
  pointer-events: none;
}

input:focus ~ label {
  top: -6px;
}
<form class="form">

  <div class="field">
    <label>Name</label>
    <input type="text">
  </div>

  <div class="field">
    <label>Age</label>
    <input type="text">
  </div>

</form>
Community
  • 1
  • 1

1 Answers1

9

To create this with just css you need to change order of input and label so you can use + selector. Then you can use transform: translate() on label when you focus input

form {
  display: inline-block;
}
.field {
  padding-top: 10px;
  display: flex;
  flex-direction: column;
}
label {
  order: -1;
  padding-left: 5px;
  transition: all 0.3s ease-in;
  transform: translateY(20px);
  pointer-events: none;
}
input:focus + label {
  transform: translateY(-2px);
}
<form class="form">
  <div class="field">
    <input type="text">
    <label>Name</label>
  </div>

  <div class="field">
    <input type="text">
    <label>Age</label>
  </div>
</form>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • hey man thanks! its not really working though. Should be the other way around –  Apr 28 '17 at 09:52
  • 1
    nice man! is there anyway to have it so that if the box contains text that I can keep it above? Guess I will need to do that with js as i am not using `required` –  Apr 28 '17 at 09:56
  • I think you will have to use jquery to detect if input has value or not. – Nenad Vracar Apr 28 '17 at 10:00
  • 2
    If you are going to use jquery then you don't need to change order in css or html at all you can just do this https://jsfiddle.net/Lg0wyt9u/1855/ – Nenad Vracar Apr 28 '17 at 10:06
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/142898/discussion-between-raul-rodriguez-and-nenad-vracar). –  Apr 28 '17 at 10:13