Making a responsive login form with bootstrap with an example. How to make the form label transition persist after I add text?

Viewed 70

I'm trying to build a nice responsive login form with bootstrap but I'm facing an interesting issue.

I would like to make the label to move away from the form input when a text is inside it and I can do that! But the problem is that when I click outside of the login form the label goes back to the middle. How can I force the transition to persist so that when a text is inside my form the label is kept out of the way?

Here is nice gif with the issue to make it easy visualize

here is the fiddle link: https://jsfiddle.net/d10ayfw5/

gif image css fail

body {
  margin: auto;
  padding-top: 30px;
  max-width: 300px;
}

div {
  margin: 20px 0 20px 0;
}

.form-outline {
  position: relative;
  width: 100%;
  font-size: 1rem;
  font-weight: 400;
  transition: all .2s linear;
}

.form-control:active~.form-label {
  transform: translateY(-1.5rem) translateY(.1rem) scale(.8);
  background-color: rgb(255, 255, 255);
}

.form-control:focus~.form-label {
  transform: translateY(-1.5rem) translateY(.1rem) scale(.8);
  background-color: rgb(255, 255, 255);
}

.form-control~.form-label {
  position: absolute;
  top: 0;
  left: .75rem;
  padding-top: .5rem;
  pointer-events: none;
  transition: all .2s ease-out;
  color: rgba(0, 0, 0, .6);
  margin-bottom: auto;
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

<div class="container d-flex align-items-center">
  <div class="row">
    <div class="col-md-2">
      <form>
        <div class="form-outline mb-4">
          <input type="email" id="form1Example1" class="form-control" />
          <label class="form-label" for="form1Example1">
                Email address
              </label>
        </div>

        <div class="form-outline mb-4">
          <input type="password" id="form1Example2" class="form-control" />
          <label class="form-label" for="form1Example2">Password</label>
        </div>

        <button type="submit" class="btn btn-primary btn-block">
              Sign in
        </button>
      </form>
    </div>
  </div>
</div>

1 Answers

First you need to add empty placeholder=' ' to input elements.

So you can use :placeholder-shown pseudo-selector, whether or not they have a value. Also, from the Selectors spec: Selectors spec

input:not(:placeholder-shown) ~ .form-label {
   transform: translateY(-1.5rem) translateY(.1rem) scale(.8);
   background-color: rgb(255, 255, 255);
}

this solution is css-only and browser-compatible for majors. can-i-use:placeholder-shown

Related