If you want to achieve this using only HTML and CSS, there is a solution available.
You may be able to refine the code further, but here's a brief concept for you to consider.
HTML
<div class="wrapper">
<input id="name" type="text" placeholder="Username" />
<label for="name"></label>
</div>
CSS
.wrapper {
position: relative;
width: 200px;
}
input {
width: 100%;
background: none;
padding: 10px;
border: none;
outline: none;
margin-top: 10px;
}
label {
position: absolute;
top: 100%;
left: 0;
width: 100%;
height: 2px;
background: rgba(0, 0, 0, 0.4);
}
label:after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 0;
height: 2px;
background: rgba(0, 0, 0, 0.8);
transition: 0.4s;
}
input:focus ~ label:after {
width: 100%;
}
Demo
Codepen Pen
Material Inputs with a floating Label
If you're interested in adding the feature of floating labels, check out this enhanced version.
I have retained the HTML structure as similar to the original idea as possible. After some trial and error, I managed to make it work by adjusting the structure slightly. I removed the placeholder tag from the input and instead added a data attribute on the parent div called placeholder. This attribute is necessary for the upward swipe effect when focusing on the input.
Additionally, a bit of JavaScript is required to apply a class to the parent element.
HTML
<div class="wrapper" data-placeholder="Username">
<input id="name" type="text" />
<label for="name"></label>
</div>
CSS
.wrapper {
position: relative;
width: 200px;
}
input {
width: 100%;
background: none;
padding: 10px;
border: none;
outline: none;
}
label {
position: absolute;
top: 100%;
left: 0;
width: 100%;
height: 2px;
background: rgba(0, 0, 0, 0.4);
}
label:after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 0;
height: 2px;
background: rgba(0, 0, 0, 0.8);
transition: 0.4s;
}
input:focus ~ label:after {
width: 100%;
}
.wrapper:before {
content: attr(data-placeholder);
position: relative;
top: 30px;
left: 10px;
color: rgba(0, 0, 0, 0.4);
transition: 0.3s;
z-index: -1;
}
.wrapper.clicked:before {
color: #000;
top: 0;
left: 0;
}
.wrapper.clicked.filled:before {
color: rgba(0,0,0,0.4);
}
jQuery
$("input").focus(function() {
$(this).parent().addClass("clicked");
if ($(this).val().length > 0) {
$(this).parent().removeClass("filled");
}
});
$("input").blur(function() {
if ($(this).val().length > 0) {
$(this).parent().addClass("filled");
} else {
$(this).parent().removeClass("clicked filled");
}
});
Demo
Codepen Pen