I was playing around on codepen
trying to find playful ways of animating UI — without using animation
or transition
properties. Just tiny movements.
Came up with this and thought I'd share it:
Try typing more than 12 characters.
How it works.
First, we use the pattern
attribute alongside required
.
This allows us to target the input with the :valid
and :invalid
pseudo-classes.
The pattern attribute has a regular expression that matches any string from 1 to 12 characters long. If the input's value is in that range we can select it in our css
using the :valid
pseudo-class, otherwise use the :invalid
pseudo-class.
<input required pattern="(\S|\s){1,12}">
Now we style the input to tilt to the right if it's invalid. If it's valid it stays level:
input:invalid {
transform:rotate(1deg);
}
But, when the input is empty it's also invalid, and will tip right. We want to give the impression the text has weight. So if the input is empty it should tip the opposite way.
To select the empty input we need to do something a bit hacky.
We can use the pseudo-class :placeholder-shown
— it allows you to style an input only when it is displaying a placeholder.
It requires a valid placeholder value to work. But if you don't want a placeholder you can use a space:
<input required pattern="(\S|\s){1,12}" placeholder=" ">
Then we add the styles to get it to tilt to the left when empty:
input:invalid {
transform:rotate(1deg);
}
input:placeholder-shown {
transform:rotate(-1deg);
}
That works, but it makes the page a bit disorienting. Better to only style the input once the user has interacted with it.
Here we'll add the tilt only if the input has been focused or already filled:
input:placeholder-shown:invalid {
transform:rotate(0deg);
}
input:placeholder-shown:invalid:focus {
transform:rotate(-1deg);
}
input:invalid {
transform:rotate(1deg);
}
Thats it. Except for some basic styles added to the codepen.
I like this, it really makes me want to balance out the text.
It could definitly be improved though:
- You could make it more universal by reversing the tilt when the text-direction is right-to-left with
:dir(rtl)
- It only works with a range starting from 1. Finding a
css
only solution for say, choose a password between 10 and 16 characters long* would be interesting. Otherwise it could usejs
. - Add
IE 10-11
support with:-ms-placeholder-shown
Top comments (3)
Neat. I think in practice this would get tiresome if used on a form with more than one or two inputs. But for, say, an email input for notifications or the like if could be just the right amount of character.
Thanks. Yes totally. Cute for one input maybe. Pretty sure it would drive everyone nuts.
Yay, CSS hacks!