Create Material Design Animated Placeholder Using CSS

Google material design is becoming popular in web trends. Lot of websites are starting to use material design in their UI. In this post, let’s see how to create an animated input box placeholder in material design style using CSS only. No need for javascript.

create-material-design-animated-placeholder

Google material design is a design language developed by google. Acquiring it in your UI design will make your website cool and trendy.

Basic HTML


<!DOCTYPE html>
<html>
<head>
 <title>Create Material Design Animated Placeholder Using CSS</title>
</head>
<body>

 <div class="field">
 <input type="text" name="user" required><br>
 <label>Enter Username</label>
 </div>
 
 <div class="field">
 <input type="password" name="password" required><br>
 <label>Enter Password</label>
 </div>

</body>
</html>

Basically, we have two blocks with two input boxes and labels. It is important to group your input fields and labels with an outer element like div otherwise the animation won’t work properly.

CSS


		.field{
			margin-bottom: 30px;
		}
		input{
			border:none;
			border-bottom: 3px solid #aaa;
			width: 80%;
			outline: 0;
			font-size: 24px;
		}
		label{
			    color: #1BA6AF;
			    position: absolute;
			    margin-top: -30px;
			    pointer-events: none;
			    transition: all 0.2s ease;
			    -webkit-transition: all 0.2s ease;
			    -moz-transition: all 0.2s ease;
			    -o-transition: all 0.2s ease;
			    font-size: 24px;
		}

		input:focus ~ label, input:valid ~ label{
			margin-top:-40px;
			font-size: 10px;
		}
		input:focus, input:valid{
			border-bottom-color: #555;
		}

label position is set to absolute and top margin is set to -30px so that the label fits inside of input box and acting as a placeholder.

It is important to use pointer-events: none;, otherwise you may not be able to click on the label covered part of input fields.

The styles inside of input:focus ~ label applied to label tag next to input box on focus. If you do not have outer div (.field) This is applied to all label tags.

If we do not have input:valid ~ label, the place holder will come back to its position after the focus blurred from the input box.

It is necessary to use required attribute in input box to make the pseudo selector :valid to work.

input:focus, input:valid is optional as it changes the border color of the input fields.

That’s it. Use this code and give your feedback below.


Anand Roshan

Author: Anand Roshan

An entrepreneur, programmer and a passionate artist who loves to work independently. Get social: Twitter | Google + | Artist Page

Leave a Reply

Your email address will not be published. Required fields are marked *