Mark
Mark

Reputation: 1679

Unexpected behavior with label transition on active state for input

Why is there a gap on the label when it's left:0 and absolutely positioned?

Trying to recreate the UI similar to Material design. I have tried using translateY(-6px) or whatever, but that isn't dynamic for labels with more characters.

.formField {
  position: relative;
  height: 40px;
}

.form {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 40px;
}

.label {
  position: absolute;
  top: 0;
  left: 0;
  transform: translate(0, 24px) scale(1);
  transition: all .3s ease-in;
}

input {
  position: absolute;
  bottom: 0;
  left: 0;
}

input:focus+.label {
  transform: translate(0, 1.5px) scale(.75);
}
<div class="formField">
  <form class="form">
    <input type="text" class="name" />
    <label for="name" class="label">Hello</label>
  </form>
</div>

Upvotes: 0

Views: 90

Answers (1)

ksav
ksav

Reputation: 20840

By default, the origin of a transform is "50% 50%", which is exactly in the center of any given element.

Try adding transform-origin: bottom left; to your .label

.formField {
  position: relative;
  height: 40px;
}

.form {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 40px;
}

.label {
  position: absolute;
  top: 0;
  left: 0;
  transform-origin: bottom left;
  transform: translate(0, 24px) scale(1);
  transition: all .3s ease-in;
}

input {
  position: absolute;
  bottom: 0;
  left: 0;
}

input:focus+.label {
  transform: translate(0, 1.5px) scale(.75);
}
<div class="formField">
  <form class="form">
    <input type="text" class="name" />
    <label for="name" class="label">Hello</label>
  </form>
</div>

Upvotes: 2

Related Questions