Build a text field with animation like material UI

The Problem

The project in my company request me a text field with a anmiation. The requirement is the placeholder inside the input with move to top when the input was focused and the valid value.

Build the layout

To get stared we must build the basic layout with html structure.

<div class="wrapper">
    <input class="input" required />
    <label class="label">
      <!-- we need the span tag because it need to specific style for text inside -->
      <span>
        Your label
      </span>
    </label>
  </div>

Code CSS for the layout

/* add basic styles for input */
.input {
  padding: 10px 20px;
  border-radius: 5px;
  border: 1px solid #0085ca;
  outline: none;
  background-color: #e8eff5
}

/* Change position offset top and left when input focused or valided */
.input:focus + .label, .input:valid + .label {
  top: -6px;
  font-size: 13px;
  color: #0085ca;
  left: 10px
}

/* Move label into input and disable user event on it */
.label {
  position: absolute;
  left: 20px;
  top: 10px;
  color: #ccc;
  pointer-events: none;
  display: flex;
  transition: .2s ease;
}

/* before and after of label as the layer for backgroud of haft their parent */
.label::before {
  transition: all .2s ease;
  position: absolute;
  height: 50%;
  width: 100%;
  content: '';
}

.label::after {
  transition: all .2s ease;
  position: absolute;
  height: 50%;
  width: 100%;
  content: '';
  top: 50%;
}

/* Span have text for label, it will put on top of label::after, label::before */
span {
  position: relative;
  z-index: 99;
}

/* Change the backgroud color following their parent */
.input:focus + .label::after {
  background: #e8eff5;
}

.input:focus + .label::before {
  background: #fafafa;
}

The key words of this solution is we use the pseudo class to hide the border of input. Then use the span tag with big z-index what will help the text put on top of the ::before and ::after.

Demo

You can see and play with in on my jsbin.

Thanks

@[P-Duy] for the solution you suggest for me.

Comments

Contact for work:Skype
Code from my 💕