Quantcast
Channel: frag (frăg)
Viewing all articles
Browse latest Browse all 40

CSS fun: labels that change colour when their input is focused

$
0
0

This is the sort of UX that should be easy to do, but is not.

CSS pseudos allow us to style different form input states, like input:focus. This is fine but ever wanted to also highlight the label element for that input? You just can’t do it.

Typical markup is:

<label for="email">LOGIN</label>
<input required type="email" name="email" id="email" class="dark-input" />

CSS3 has no backreference (reverse combinator) selector so we can’t go input:focus < label or whatever syntax (eg. ! in MooTools Slick).

What you can do is apply a sibling style instead by re-arranging your DOM

<input required type=”email” name=”email” id=”email” class=”dark-input” />
<label for=”email”>LOGIN</label>

The above HTML now allows for the natural CSS selector of:

input:focus + label {
    color: white;
}

But now the label looks like it’s underneath the control. You can move it back up by using some translate() to offset the order:

label {
    transform: translate(0, -30px);
    color: #ccc;
}

Want to see it in all in action? Here comes batman…


Viewing all articles
Browse latest Browse all 40

Trending Articles