Creating material design labels with CSS

A few months ago Google released design guidelines, Material Design.

Along with many other elements, it also provides details on form labels. In this post I have experimented with CSS to implement that design. We will not be using any JavaScript. Just CSS. For those who can't wait to read till end and want to know the technique involved, here it is: position: absolute;

What we do is make the label element come over input and when input is focused, we make label go up.

Demo

HTML Markup

Lets start by defining our HTML markup first. We'll simply use:

<div class="field">
    <input type="text" id="name" />
    <label for="name">Your Name</label>
</div>

Here we used the outer <div class="field"> to contain our elements as we are going to use position absolute.

CSS

Now comes the basic CSS.

.field {
    position: relative;
}
.field input {
    display: block;
    width: 100%;
    padding: 5px;
    outline: none;
    color: #727272;
    font-size: 20px;
    font-weight: 100;
    border: 0;
    border-bottom: 1px solid #424242;
}
.field input:focus {
    border-bottom: 1px solid #00B8D4;
}
.field label {
    display: block;
    padding: 5px;
    padding-left: 7px;
    color: #424242;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.6s; /* add browser specific prefix */
}
/* To change the color of label and input text when cursor is in input field or over it */
.field input:focus + label, input:hover + label {
    color:  #00B8D4;
}

With this CSS we've set come basic styling for our input field and label. Also notice, we made both of them display:block to cover the full width of outer element which in this case is .field

Make it happen

Now here's the real piece of code that make our label as we want.

First we'll bring the label on input. position: absolute to rescue.

.field label {
    position: absolute;
    top: 0;
}

We've brought the label over input. How do we make it go up when cursor enters the input? Simple; use CSS pseudo selector :focus like this:

.field input:focus + label {
    top: -18px;
    width: 100%;
    font-size: 12px;
}

Note: You can also use :valid instead/with :focus to make the change when user has entered at least one character. :valid will, of course, depend on the type of input.

Thoughts or Suggestions: