You already know that inline styles are "bad practice." Inline styles aren't reusable like CSS in separate files is, and thus, inefficient bloat. Unless of course, when it isn't. There are some instances where inline styles make perfect sense. Perhaps you have an application where user's pick their favorite color, and then you set the background of the body to that. Using an inline style in that case is actually more efficient than external CSS, since it's specific to one user and one element.
Now let's say you want to animate to a value set in an inline style. Say you want to animate a progress bar. You start at zero, and need to go up to any arbitrary value. Perhaps a call to the server tells you how complete an upload is and you set the value from that.
In a post I did nearly a year ago, I lamented that you can't animate to an inline style. You can't declare a keyframe in inline styles and you don't know what final value to animate to in the external CSS. Alas I was wrong, as I didn't know about this bonafide little CSS trick.
Here's the trick: just omit the to
or 100%
declaration from the @keyframe:
@-webkit-keyframes progress-bar { 0% { width: 0; } } @-moz-keyframes progress-bar { 0% { width: 0; } }
Then you call the animation on the progress bar:
.progress-bar > div { -webkit-animation: progress-bar 2s; -moz-animation: progress-bar 2s; }
And just like that, the progress bar will animate itself up to the value set by the inline style.
Here's a Dabblet if you wanna mess with it.
Special thanks to Michael Paryna who emailed me about this and got me to give it a try.
Animate to an Inline Style is a post from CSS-Tricks
Sent from my iPhone
No comments:
Post a Comment