Floating Label (Using :placeholder-shown pseudo class)
Concept for floating label for the input element (using :placeholder-shown pseudo class and placeholder), When input is empty user doesn't see the label but when he starts typing the label appears above the input
by Konstantin Rouda
June 08, 2017
HTML
<div class="c-form__field">
<input type="text" class="c-form__input o-input" id="name" placeholder="First Name" />
<label for="name" class="c-form__label">First Name</label>
</div>
<div class="c-form__field">
<input type="password" class="c-form__input o-input" id="name" placeholder="Password" />
<label for="name" class="c-form__label">Password</label>
</div>
CSS
HTML {
font-size: 150%;
line-height: 1.5;
box-sizing: border-box;
}
BODY {
color: #000;
}
*, *::before, *::after {
box-sizing: inherit;
}
* + * {
margin-top: 1.5rem;
}
/*Actual Style*/
/*============
C-Form-Label
==============*/
.c-form__label {
position: absolute;
left: .5rem; top: .25rem;
transform: translateY(10%);
opacity: 0;
transition: transform .25s, opacity .15s;
transition-timing-function: ease-in-out;
}
/*For the browsers that DON'T support :place-holder-shown pseudo-class*/
/*.c-form__input:focus ~ .c-form__label {
opacity: 1;
transform: translateY(0%);
}*/
/*For the browsers that DO support :place-holder-shown pseudo-class*/
.c-form__input:not(:placeholder-shown) ~ .c-form__label {
opacity: 1;
transform: translateY(0%);
transition-duration: .3s, .2s;
}
/*UI Style*/
/*============
C-Form-Field
==============*/
.c-form__field {
position: relative;
max-width: 50%;
margin-left: auto;
margin-right: auto;
padding: 1.5rem .5rem;
background: #fff;
box-shadow: 0 1px 2px rgba(0, 0, 0, .1), 0 2px 4px rgba(0, 0, 0, .15);
}
/*============
C-Form-Label
==============*/
.c-form__label {
margin: 0;
color: rgb(109, 143, 204);
}
/*============
O-Input
==============*/
.o-input {
font-size: 1rem; /* default font-size for input is 12-13 px */
}
.o-input::-ms-placeholder {
color: rgba(50, 50, 50, .2);
}
.o-input::-webkit-placeholder {
color: rgba(50, 50, 50, .2);
}
.o-input::placeholder {
color: rgba(50, 50, 50, .2);
}
/*============
C-Form-Input
==============*/
.c-form__input {
border: none;
border-bottom: 1px solid rgba(70, 70, 70, .2);
outline: none;
background-image: linear-gradient(to right, rgb(117, 164, 247), rgb(187, 228, 255));
background-size: 0% 3px;
background-position: 0% 105%;
background-repeat: no-repeat;
transition: background-size .1s ease-in-out;
}
.c-form__input:focus {
//border-bottom-color: cornflowerblue;
background-size: 100% 3px;
...