Ry Van Ry Van - 6 months ago 22
HTML Question

CSS transition animation not working

This is my code and I am trying to make the label float while the input box is focused, which is similar to angular material animation. I succeeded with the logic but the animation doesn't seems to work.

I am using pure CSS and HTML.



.space {
padding: 5px;
margin-top: 30px;
}
.space .form_input {
display: inline-block;
}
.space .form_input input {
border: none;
border-bottom: solid thin #d6d6d6;
background: none;
position: absolute;
box-shadow: initial;
}
.space .form_input input:focus {
border: none;
border-bottom: solid thin #d6d6d6;
outline: none;
}
.space .form_input input:focus + label {
transition: all 0.7s ease-out;
top: -20px;
}
.space .form_input input:valid + label {
top: -20px;
}
.space .form_input input[value=""] + label {
border: green;
}
.space .form_input input ~ label {
-webkit-transition: all 0.7s ease-out;
-moz-transition: all 0.7s ease-out;
-ms-transition: all 0.7s ease-out;
-o-transition: all 0.7s ease-out;
transition: all 0.7s ease-out;
pointer-events: none;
color: red;
position: relative;
}

<form class='space'>
<div class='form_input'>
<input name='email' id='email' required>
<label for='email'> Email: </label>
</div>
</form>




Answer

You have to define the initial position of animation (without focus) using...

.space .form_input input ~ label {top: 0;}

.space {
  padding: 5px;
  margin-top: 30px;
}
.space .form_input {
  display: inline-block;
}

.space .form_input input {
  border: none;
  border-bottom: solid thin #d6d6d6;
  background: none;
  position: absolute;
  box-shadow: initial;
}
.space .form_input input:focus {
  border: none;
  border-bottom: solid thin #d6d6d6;
  outline: none;
}
.space .form_input input:focus + label {
  transition: all 0.7s ease-out;
  top: -20px;
}
.space .form_input input:valid + label {
  top: -20px;
}
.space .form_input input[value=""] + label {
  border: green;
}
.space .form_input input ~ label {
  transition: all 0.7s ease-out;
  pointer-events: none;
  color: red;
  position: relative;
  top: 0;
}
<script src="https://leaverou.github.io/prefixfree/prefixfree.js"></script>

<form class="space">
  <div class="form_input">
    <input id="email" name="email" required="" />
    <label for="email"> Email: </label>
  </div>
</form>