Layout · 16 of 23

Floating Label

Input focus interaction

HTML · CSS · No dependencies · MIT

HTML

<!-- placeholder=" " is required: :placeholder-shown is how CSS
     knows whether the input is empty -->
<div class="input-group">
  <input type="text" id="floatInput" placeholder=" ">
  <label for="floatInput">Email Address</label>
  <div class="input-border"></div>
</div>

CSS

.input-group {
  position: relative;
  width: 100%;
  max-width: 280px;
  margin-top: 1rem;
}

.input-group input {
  width: 100%;
  padding: 0.5rem 0;
  background: transparent;
  border: none;
  border-bottom: 1px solid #444;
  color: #fff;
  outline: none;
}

.input-group label {
  position: absolute;
  top: 0.5rem;
  left: 0;
  color: #666;
  pointer-events: none;
  transition: 0.3s ease;
  font-size: 1rem;
}

/* Float the label when focused OR when the input has text */
.input-group input:focus + label,
.input-group input:not(:placeholder-shown) + label {
  top: -12px;
  font-size: 0.75rem;
  color: #7c5cff;
}

/* Accent underline grows from the left on focus */
.input-border {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 0;
  height: 2px;
  background: #7c5cff;
  transition: width 0.3s ease;
}

.input-group input:focus ~ .input-border {
  width: 100%;
}