Destro Destro - 6 months ago 23
CSS Question

Input field change it's position while on focus

I am trying to create a form with material design. While not focus it looks good but when the field is focused, it's position towards left.
You can check the image for more details, and you can also see the distance between two field.

enter image description here

enter image description here

Here is HTML:



form.login-form {
display:block;
position:relative;
margin: 40px auto;
}
label{
display: inline-block;
position: relative;
top:0px;
left:-184px;
color:#999;
font-family:'Helvetica', sans-serif;
font-size:16px;
z-index:1;
transition: all 0.2s ease-in;
}
input{
display:inline-block;
position: relative;
background:none;
border:none;
border-bottom: 1px solid #aaa;
font-family: 'Helvetica', sans-serif;
font-weight: lighter;
font-size: 16px;
z-index:2;
}
input:focus , input:valid{
outline:none;
border-bottom: 1px solid #830303;
position: relative;
}
input:focus + label,input:valid + label{
top:-17px;
font-size:11px;
color:#830303;
background-position: 0 0;
}

<form action="#" method="" class="login-form">
<div class="loginformgrid">
<div>
<input type="text" name="username" required autocomplete="off">
<label for="username">Username</label>
<input type="password" name="password" required autocomplete="off" >
<label for="password">Password</label>
<button class="login-button" type="submit" value="submit">Login</button>
</div>
<div class="belowloginformgrid">
<div>
<input type="checkbox" name="remeberme"> Remember me
<a href="#">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Forgot password?</a>
</div>
</div>
</div>
</form>




Answer Source

The issue your having is due to the label resizing on focus. As you have the transition:all on label which applies it to all the properties and as your font size is getting smaller so the label takes in less space and hence the default inline spacing of your controls shrinks. Set the width of your label to a default size to fix it so that it does not change with the transition and remains the same for it to not shrink the space in between.

label{
  display: inline-block;
  position: relative;
  top:0px;
  left:-184px;
  color:#999;
  font-family:'Helvetica', sans-serif;
  font-size:16px;
  z-index:1;
  transition: all 0.2s ease-in;
  width:100px; /* Add this to keep it same when transitioning*/
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download