CSS - iOS style Floating Label

http://dbushell.com/

by katalin_2003

HTML

<div class="field">
    <label class="field__label" for="form-name">Name</label>
    <input class="field__input" type="text" required placeholder="Name…" id="form-name">
</div>
<p>This technique uses CSS (no JavaScript). <strong>Warning:</strong> The <code>:valid</code> selector is used meaning it will only work with <code>type="text"</code>. Otherwise with <code>type="email"</code> for example, the label won't appear until the input value actually validates.</p>
<hr>
<div class="field">
    <label class="field__label" for="form-email">Email</label>
    <input class="field__input" type="email" required placeholder="[email protected]…" id="form-email">
</div>
<p><strong>Browser support:</strong> unforunately the <code>placeholder</code> attribute requires IE10+ so in IE9 you get no label whatsoever (so show the label by default and progressively enhance this fancy stuff).</p>
<hr>

CSS

@charset"UTF-8";
body {
    font-family: sans-serif;
}
 .field {
    position: relative;
    padding-bottom: 1.875em;
    margin-bottom: 1.875em;
    max-width: 20em;
}
.field__label {
    display: block;
    position: absolute;
    top: 1.25em;
    font-size: 0.75em;
    line-height: 1.25em;
    font-weight: bold;
    color: #2996cc;
}
.field__input {
    position: absolute;
    display: block;
    box-sizing: border-box;
    font-size: 1em;
    line-height: 1.25em;
    padding: 0.3125em 0;
    height: 1.875em;
    width: 100%;
    border: 0;
    outline: none;
    border-bottom: 0.125em solid #bbb;
}
.field__input:valid {
    position: relative;
    top: 1.875em;
    margin-top: -1.875em;
}
.field__input:focus {
    border-bottom-color: #2996cc;
}
body {
    padding: 1.875em;
}
hr {
    display: block;
    clear: both;
    margin: 1.875em 0;
    border: 0;
    outline: 0;
    height: 2px;
    background: #ddd;
}

JavaScript

// remove the :valid pseudo-class from .field__input:valid to show the label all the time if you're planning on supporting IE9 and below