two years agoCSS3 animations demonstrated with snow

This winter we have had an unusually snowy time of things, as a matter of fact so has the whole of the UK. As a Clearleft christmas snowy surprise I wrote a CSS3 snow bookmarklet.

If you are running a WebKit based browser you can make it snow on anywhere on the internet by dragging the following bookmarklet into your toolbar, sending any site into a mini snowstorm!

Let it Snow!

I based the snow in part on the leaf example on the WebKit blog.

JavaScript is only just to add the snowflakes in their starting position (and naturally in order for it to be a bookmarklet) but all the animation and styles are done in pure CSS. So if you wanted to do this without any JavaScript at all you could just start with the snowflake elements directly in the source and it would work fine.

For the snowflakes themselves I had a lot of fun looking through the Unicode list of snowflakes, and asterisks trying to find the prettiest snowflakes ❆, ❅, ❄, ✳, they are in an array and the sizes are in another array. Every snowflake is an absolutely positioned div with a span inside, we will come to that later. When a snowflake is chosen a size and a character are chosen at random. the distribution of sizes is controlled by the proportion of the size class in the array:

var flakes = ['2746', '2745', '2744', '2733'];
var sizes = ['tiny', 'tiny', 'tiny', 
  'small', 'small', 'small', 'small', 
  'medium', 'medium', 'medium', 'medium', 'medium', 'medium', 
  'large', 'massive'];

When the snowflakes are positioned, a random side (left or right) and a percentage between 0 and 60 is chosen to set the position absolute values, this makes it work nicely when you resize the browser and means there is a higher concentration of snowflakes in the center 20% of the screen. They also needed an epic-ly large z-index because this is going to be used as a bookmarklet and you don't know what will be on the page it is used on.

Another consideration in the setup was that white snowflakes would not be seen on white pages so a text shadow was added to make it stand out, I used rgba for this to make it blend in better with any background color.

text-shadow: rgba(0, 0, 0, 0.7) 1px 1px 2px;

There are two main animations for each snowflake, fading and dropping. The span inside the snowflake does the spinning. These animations are set up and given a reference-able name in the CSS file:

/* Hides a snowflake towards the very end of the animation */
@-webkit-keyframes fade {
	
  /* Show a snowflake while into or below 85 percent 
     of the animation and hide it, otherwise */

  0%   { opacity: 1; }
  85%  { opacity: 1; }
  100% { opacity: 0; }
}

@-webkit-keyframes drop {
	
  /* Makes a snowflake fall from -50px to 650px 
     pixels in the y-axis starting at -50 so as 
     to appear to be falling from above 
     the screen not starting at the top */

  0%   { -webkit-transform: translate(0px, -50px); }
  100% { -webkit-transform: translate(0px, 650px); }
}

The named animation group contains sub groups, rule blocks where the selector is one moment in the animation. When the animation runs it looks at the timeline of keyframes and smoothes the animation accordingly, for example in the fade animation above, the opacity stays at 1 until 85 percent through its animation (aka one drop) where it then begins a smooth fade to 0 over the last 15% of the time. If we had omitted that middle step and just had opacity set to 1 at 0% and to 0 at 100% then the fade would be a smooth fade over the duration of the whole animation.

You can also set the 'moment' of the keyframe using the keywords from and to, this is effectively the same as 0% and 100%. For simple animations this probably would suffice but I find using percentages gives you a greater degree of control over the pace of your animation.

-webkit-animation-name: 'fade, drop'

Because we know we have two animations being applied to each snowflake div in JavaScript we can give the other animation properties two values and know that they apply to the two animations respectively.

-webkit-animation-iteration-count: infinite, 20;

The animation-iteration-count states how many times an animation should run. We are not too fussed about the fade but we want to only have each snowflake fall from the sky 20 times before disappearing, just in case the bookmarklet is used and left open in a tab it shouldn't continue indefinitely.

-webkit-animation-direction: normal, normal;

Options for this are normal and alternate. Normal behaves exactly as you have specified in your keyframes, alternate behaves normally on odd iterations and reversed on even iterations

-webkit-animation-timing-function: linear, ease-in;

There are quite a few options you can play with for this property ease linear ease-in ease-out ease-in-out and if you really know your animation maths you can go wild with cubic-bezier(X, X, X, X). Basically this describes the acceleration of the animation e.g. linear is all at the same speed, ease-in has a little warm up first, ease-out warms down and ease-in-out does both. I wanted the snowflakes to ease gradually in before reaching a constant speed.

-webkit-animation-duration

We are setting the animation-duration in Javascript because it needs to be randomised to avoid all the flakes falling at the same rate. This is being set at a random time between 5 and 11 seconds (trial and error got these magic numbers). Ideally I would have set the range based on the size of the snowflake which would have been cool, I could easily have made the larger ones fall faster than smaller ones, but I didn't think of that at the time.

-webkit-animation-delay

How long until the first snowflake starts falling? I have set this in Javascript to be instant for the first snowflake (remember it still has to fall 'into the screen' when it starts) and then a random amount of time between 4 and 8 seconds for the others. This was important with so few snowflakes because we need to spread them out so they don't all fall at the same time and look like a continuous snow storm

Naturally there is an animation shorthand property should you wish to specify everything at once.

With our snowflakes falling and fading nicely, all that remains is the spinning. in the JavaScript I set a random animation to the span inside the snowflake div that contains the snowflake character. The animation is then either clockwiseSpin or counterclockwiseSpin

@-webkit-keyframes clockwiseSpin {
  /* Rotates a snowflake from -50 to 50 degrees in 2D space */
  0%   { -webkit-transform: rotate(-50deg); }
  100% { -webkit-transform: rotate(50deg); }
}

@-webkit-keyframes counterclockwiseSpin  {
  /* Rotates it from 50 to -50 degrees in 2D space */
  0%   { -webkit-transform: rotate(50deg); }
  100% { -webkit-transform: rotate(-50deg); }
}

We then set the properties explained above for the span.

-webkit-animation-iteration-count: infinite;
-webkit-animation-direction: alternate;
-webkit-animation-timing-function: ease-in-out;

-webkit-transform-origin: 50% -100%;

The spinning should be infinite and to add to randomness we need to use the 'alternate' value for direction and ease-in-out as the timing function, the offset transform origin plays with the rotation transform inside the spinning animation in order to make it seam like it is floating on a light snowy breeze.

To finish it off then the JavaScript is wrapped in a self executing function, the CSS is added to the head of the document from the main JavaScript file rather than having to bulk that into the bookmarklet. The JavaScript on is then splurted into the head of the document. The bookmarklet looks like this:

javascript:(function(){var%20s=document.createElement('script');s.src='http://j.mp/7ZZuRu';document.getElementsByTagName('head')[0].appendChild(s);})()

All that remains is to just Let it Snow!

Further reading

These two articles on the WebKit blog have some good demo's on the use of animation. My 24ways article goes into a bit more detail on transforms and Tim Van Damme's great 24ways article has a supurb space animation demo which is worth looking at. The spec is available on the w3c site.

2108 comments

  1. Snowstorm is a Javascript-driven snow effect that can be easily added to web pages. It is free for use, and easy to set up. A single Javascript file provides the functionality required. No images are used for the snow effect.

    Web Design Company 26th January 2010 04:47permalink.

  2. vHXm1C Howdy, and <a href="http://kamagra-fda.viviti.com">generic kamagra</a> and http://kamagra-fda.viviti.com generic kamagra and vwjsu and

    mobic online 21st March 2010 16:48permalink.

  3. Your post is really informative for me. I liked it very much.

    blanc pain watch 10th July 2010 09:44permalink.

  4. I know a software named Easy Video Converter can Convert Video To AVI, Video To MPEG,

    malin 13th July 2010 03:26permalink.

  5. Thanks for the great app using webkit. I like it. used stationary bikes | baby back carrier

    stationary bikes 19th July 2010 07:28permalink.

  6. I like your post and all you share with us is up to date and quite informative, i would like to bookmark the page so i can come here again to read you, as you have done a wonderful job.

    phoenix carpet cleaning 29th July 2010 16:50permalink.

  7. So far I always get stucked at the reforming stage. Anyone here know a helpful and comprehensive tutorial module? Channel - Shoulder Bags

    ChannelBlu 30th July 2010 11:29permalink.

  8. I love the leaf example... great Wii Console

    James Albright 2nd August 2010 22:01permalink.

  9. We have smart louis vuitton outlet and nike dunks also louis vuitton bags

    kirk 3rd August 2010 14:49permalink.

  10. Great Buddy how you know about this in very details, it is really very interesting and knowledgeable things.
    ___________
    <a href="http://personalwealthacademy.com/internet-coaching.php">internet coaching</a>

    hilda_dada 3rd August 2010 19:09permalink.

  11. You really make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand. It seems too complicated and very broad for me. I am looking forward for your next post, I will try to get the hang of it! Cosmetic surgeon

    Edward 10th August 2010 12:41permalink.

  12. I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post

    thanks for this site,

    Business Marketing Strategy Information And Knowledge | Healthy Living Solution

    Information and Business Online 11th August 2010 18:30permalink.

  13. You really make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand. It seems too complicated and very broad for me. I am looking forward for your next post, I will try to get the hang of it! Medical alert systems Answering Services

    Scoden 13th August 2010 07:58permalink.

  14. Looking really informative and practical approach.Little small applications can brings lot of money for your business If you market them properly. loan software

    Linda 15th August 2010 03:10permalink.

  15. Keep 'em coming... you all do such a great job at such Concepts... can't tell you how much I, for one appreciate all you do! Acuvue Advance Astigmatism

    Acuvue Advance Astigmatism 15th August 2010 07:13permalink.

  16. I think a lot of things have been simplified in CSS3 which is why I can't wait till its become a next new standard in CSS. Always have been a huge fan of CSS. - Find all that you're looking for in womens perfume today.

    Mark M 17th August 2010 07:01permalink.

  17. Thank for you for providing this tutorial, it enlighten my idea to solve the problem I encounter! I'll bookmark it and hope could read more article from you.

    Good done!

    Jiaren 17th August 2010 13:14permalink.

  18. chiropractor in naperville hurricane bong

    John Stantom 20th August 2010 02:10permalink.

  19. I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you pos lv speedy louis vuitton neverfull artsy mm

    louis vuitton handbags 22nd August 2010 15:15permalink.

  20. Super-Duper site! I am loving it!! Will come back again - taking you feeds also, Appreciation. bench furniture

    Benn 22nd August 2010 17:50permalink.

  21. Thanks very much for this awesome Article. Nice topic to write about on my Blog. I might set a bookmark from another Website. deck storage box

    Tracy 22nd August 2010 17:52permalink.

  22. Its my great pleasure to visit your site and to enjoy your awesome post here. I like it very much. I can feel that you put much attention for these articles, as all of them make sense and are very useful miami rhinoplasty

    John 22nd August 2010 17:52permalink.

  23. nice article, i just finished bookmarking it for future reference. i would love to read on future posts. how do i configure the rss again? thanks! today articles

    Mike 22nd August 2010 17:53permalink.

  24. goods site:

    <a href="http://www.goods-in-china.com"> wholesale nike shoes,nike soccer shoes,louis vuitton handbag,abercrombie fitch shirts,polo t shirts 2010,free shipping</a>

    wholesale nike shoes 23rd August 2010 01:44permalink.

  25. goods site:

    http://www.goods-in-china.com/wholesale-price_Nike+Soccer+Shoes.html nike soccer shoes

    nike soccer shoes 23rd August 2010 01:46permalink.

  26. good site: www.goods-in-china.com

    http://www.goods-in-china.com/wholesale-price_Louis+Vuitton+handbag.html louis vuitton handbag

    louis vuitton handbag 23rd August 2010 01:48permalink.

  27. Its my great pleasure to visit your blog and to enjoy your awesome posts here. I like that a lot. I know that you put much attention for these articles, as all of them make sense and are very useful micr printer toner

    Shiney 23rd August 2010 18:08permalink.

  28. Just found this blog. excellent article. how long have you been writing? this is good writing. are you a journalist aswell? anyway, thanks again. subscribing to the rss :) best wrinkle cream

    Drona 23rd August 2010 18:09permalink.

  29. Hey This is some great thing never thought of it like that electric powered bicycle

    Brown 23rd August 2010 18:10permalink.

  30. Hey This is some great thing never tought that it could work like that, good job! half ironman training

    hayden 23rd August 2010 18:10permalink.

  31. It is hard find post say such a thing is clear like you.

    chanel handbags 24th August 2010 04:24permalink.

  32. It is hard find post say such a thing is clear like you.

    five finger shoes 24th August 2010 04:25permalink.

  33. be accepted. I have noticed that for an application, a close up photo of something interesting seams to be the way to go.

    Purely for your continued education (not as fuel to mock me with) here is a list of my rejections.

    lace front wigs 24th August 2010 05:31permalink.

  34. thanks for posting the words

    metin2 yang 25th August 2010 07:28permalink.

  35. <a href="http://www.toptoys2trade.com/power-balance-wholesale-2-c-40/ "> power balance</a>

    animal rubber bands 25th August 2010 08:54permalink.

  36. Super-Duper site! I am loving it!! Will come back again - taking you feeds also, Appreciation. Hermes Birkin 30CM black crocodile stripe Silver Hardware

    lili 26th August 2010 08:39permalink.

  37. other webmasters as well. If you will like this to shared on other forums as well, I will really like to help. I will post it with your name to make your work really help full for you as well! Keep up the good work, post more topics like this and I know the forum will really be proud of their best resources.

    one dollar cookware 27th August 2010 09:59permalink.

  38. awesome, thanks for the coding. This will help me get prepare for Christmas theme.

    symptoms of kidney infection 28th August 2010 01:39permalink.

  39. thanks for the programs above. Hope this would not crash my website. But how was the integration with websites? Can I use it on blogs as well?

    completely free dating sites 28th August 2010 01:42permalink.

  40. keep up the good work documenting all those hard work and showing it to us. The explanation is brilliant.

    make money online 28th August 2010 01:45permalink.

  41. awesome, thanks for the coding. This will help me get prepare for Christmas theme. roxbury drive louis vuitton watercolor speedy louis vuitton alma

    louis vuitton 30th August 2010 07:34permalink.

  42. This is a great post; it was very informative. I look forward in reading more of your work. Also, I made sure to bookmark your website so I can come back later. I enjoyed every moment of reading it
    And I like wearing <a href="http://www.srait.com">nfl jerseys</a>.

    wholesale nfl jerseys 31st August 2010 04:33permalink.

  43. Excellent! Thank you

    discountshoes 31st August 2010 07:01permalink.

  44. I am must say I am really surprised what the CSS actually allows and the effect you could make with only the minimal use of Javascript. Too bad not more people know of these capabilities of the CSS and use too much Javascript scripts on their pages, which then slows down their sites. I also did not know, that Safari is based on Webkit, which is open source. Interesting fact. Norwegisch Deutsch

    Norwegisch Deutsch 31st August 2010 23:00permalink.

  45. Welcome to our website. You can find various designs of coach wallet and juicy couture of simple, classic, or fashion styles here. Find the coach factory outlet will help you save a lot but enjoy the fashionable design bags for your style!

    b1@ 1st September 2010 20:59permalink.

  46. While bargain are purchasing Li-ion album acclimation the sellers will accustom to them how abounding hours that Album acclimation can come, there are added causes that are accordance to the birthmark of the Li-ion rechargeable battery. Many album buyers acquire no apprehension about abstract getting circuitous on accepting complete Action out of their laptop batteries Album adeptness pack. Like all added Li-ion rechargeable batteries; you allegation to board adversity if those are unused. Don't abode your Album Acclimation haversack nearer to chemicals or in a wet across as this will abridge your Album adeptness haversack Life.
    http://laptopbattery.mublogs.org/

    dell laptop battery charger 2nd September 2010 10:13permalink.

  47. I hope you have a nice day! Very good article, well written and very thought out. I am looking forward to reading more of your posts in the future.
    http://www.juicycouture4u.com/

    Juicy Couture 3rd September 2010 03:32permalink.

  48. Your article is ultra healthy and the tips are very usefull , thanks for sharring. holiday villa

    Maya King 3rd September 2010 07:50permalink.

  49. I hope you have a nice day! movie downloads | takers download | download the expendables

    Londo 3rd September 2010 12:39permalink.

  50. wow all those garments are so amazing and fabulous louis vuitton small ring agenda refill don't come to your blog as often as baseball cap would like, but whenever louis vuitton speedy do see some really amazing things keep up the good work! =)

    louis vuitton mini agenda refill 4th September 2010 08:50permalink.

  51. This page is a great method to connect to others. Congratulations on a job well achieved. I am anticipating your next entry. best plastic surgeons

    roger 4th September 2010 10:48permalink.

  52. The articles you have on your website are always so enjoyable to read. Good work and I will be returning often. home loan refinance

    rajan 4th September 2010 10:49permalink.

  53. Hey, I just hopped over to your site via StumbleUpon. Not somthing I would normally read, but I liked your thoughts none the less. Thanks for making something worth reading. personal training

    ragi 4th September 2010 10:50permalink.

  54. Great article you've written, is this your first website blog or have you been doing this a while? I'd be interested in reading some more of your things. Links please? online marketing ebooks

    ragini 4th September 2010 10:51permalink.

  55. I hope you have a nice day! Very good article, well written and very thought out. I am looking forward to Moncler outlet reading more of your posts in the future. Moncler

    nice 5th September 2010 09:18permalink.

  56. I hope you have a nice day! Very good article, Moncler outlet well written and very thought out. I am looking forward to Moncler reading more of your posts in the future. Moncler

    nice 5th September 2010 09:19permalink.

  57. power balance

    power balance 7th September 2010 02:29permalink.

  58. how can i contron the css3? i m a new... wholesale china cell phones

    wholesale china cell phones 7th September 2010 03:27permalink.

  59. I must admit that I always found CSS at building web pages. I mean, the learning curve is quite steep, at least in my opinion, and especially if you want to do more than just simple webpages. So it is interesting to see, what capabilities CSS (CSS3 actually) has and what one can do with it. traduttore italiano giapponese

    traduttore italiano giapponese 7th September 2010 21:17permalink.

  60. Thanks for sharing!

    Ted 8th September 2010 10:44permalink.

  61. That’s one small step for man writing CSS, this is really a cool effect and is a good reference for designers.

    Adult Dating 8th September 2010 18:38permalink.

  62. http://business-idei.narod.ru

    business-idei@yandex.ru 8th September 2010 21:21permalink.

  63. gucci tote bag is some of the finest designer shoes on today's market. As leaders in high fashion, Gucci's line always features the latest, most stylish handbags. All gucci messenger bag is made from superior material and crafted carefully and intricately to ensure the best quality. As they are high in demand and well-made, Gucci handbags garner expensive prices. You can, however, find more affordable gucci handbags on sale, if you know where to look.

    hello 9th September 2010 09:25permalink.

  64. Adult Dating Site

    GerryHenries 9th September 2010 19:59permalink.

  65. Sex Contacts Free Adult Dating Amateur Swingers

    Wooh Ram 9th September 2010 20:09permalink.

  66. I hope you never stop! This is one of the best blogs Ive ever read.

    Rolex replica 10th September 2010 05:56permalink.

  67. i like this say .very good

    christian shoes 10th September 2010 09:13permalink.

  68. Nice! Thanks very good for report,I follow your article.

    ghd straighteners 10th September 2010 11:01permalink.

  69. <a href=http://www.pphog.com/Golf-Polo.html>Golf Polo</a>
    <a href=http://www.pphog.com/Match-Polo.html>Match Polo</a>
    <a href=http://www.pphog.com/Black-Watch-Polo.html>Speciaux Polo</a>Polo Ralph Lauren Femme Nouveau Polo Femme Golf Polo Match Polo Speciaux

    pololacoste 12th September 2010 10:05permalink.

  70. thankx post good

    mirc 12th September 2010 14:47permalink.

  71. thankx goood

    Çet 12th September 2010 14:48permalink.

  72. http://www.brand-watch-supplier.com/efx-bracelet-c-52/ EFX bracelet

    power balance 14th September 2010 03:37permalink.

  73. Nice! Thanks very good for report,I follow your article.

    cosplay costumes 14th September 2010 09:21permalink.

  74. Purely for your continued education (not as fuel to mock me with) here is a list of my rejections. Moncler branson Moncler jackets Moncler outlet

    nice 14th September 2010 21:23permalink.

  75. <a href=“http://www.ssktoys.com/”>Silly Bandz</a> are not just for teens anymore! The company of the popular bracelets have released a number of UK themed bands. Orders from all over Kentucky and the country are coming in online...from Tennessee, Pennsylvania, to South Carolina. UK basketball fans want their hands on the new Coach Cal Silly Bandz.

    Silly Bandz 16th September 2010 06:49permalink.

  76. Is it real true? I was not sure about this matter as i am learning CSS. I will be opting to other versions of CSS but not as of now childcare grants

    ryan jain 16th September 2010 06:56permalink.

  77. I need CSS help for my sites on potty training boys and how to potty train a toddler its all really new to me. How much faster would it make my sites load?

    sarah genner 16th September 2010 19:43permalink.

  78. Dear friends, please temporarily stop your footsteps
    To our website Walk around A look at
    Maybe you’ll find happiness in your sight shopping heaven and earth
    You’ll find our price is more suitable for you.
    Welcome to our website http://www.clotheshops.us
    Next we come to talk about a topic:
    Why are now prices are very expensive%uFF1F
    yes Many people now have to earn more money
    to Pushing up prices
    But they didn’t find customers buy after won’t come back
    But friends %uFF0CDo you ever found
    Our website is more cost-effective price than others

    lingh 17th September 2010 01:27permalink.

  79. <a href=" http://www.rolexclassic.com/class/?mywatchclass=443">rolex</a>

    replia rolex

    replica omega

    replica breitling

    replica cartier

    replica IWC

    replica chanel

    replica watches

    All the watches here have top quality and the price is very reasonable.

    You will never ever regret to enter and take a look at.

    replica breitling 17th September 2010 03:18permalink.

  80. http://www.nicecoachhandbags.com

    coach handbags 17th September 2010 07:59permalink.

  81. I am very glad to see a guide on Css3! Jake Grand Rapids Homes For Sale

    Jake 17th September 2010 20:38permalink.

  82. headband wind protection for your

    louis vuitton 18th September 2010 15:21permalink.

  83. Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming.

    air jordan 19th September 2010 10:51permalink.

  84. Thanks a lot for enjoying this beauty article with me. I am apreciating it very much! Looking forward to another great article. Good luck to the author! all the best!

    louboutin shoes 19th September 2010 10:52permalink.

  85. Thank you for sharing all this great information. Cheap Nike Shoes louboutin shoes air max 90

    air jordan 19th September 2010 10:57permalink.

  86. This is a nice note. Nike shox Cheap Nike Shoes air max 90

    Cheap Nike Shoes 19th September 2010 11:03permalink.

  87. accent and you have yourself a costume

    lace 20th September 2010 01:03permalink.

  88. I hope you have a nice day! Very good article, well written and very thought out. I am looking forward to reading more of your posts in the future.

    Juicy Couture 20th September 2010 03:56permalink.

  89. You are a saint for assignment help providing this. Saved me uncountable HOURS. Kudos for your clarity and assignment writing completeness. Brilliant! Thanks!.

    peterson 23rd September 2010 09:04permalink.

  90. It was a very nice article! thesis help Just want to say thank you for the information you have shared. research writing Just continue writing this kind of post. Thanks. coursework writing

    james kerry 23rd September 2010 12:29permalink.

  91. I have a good website, you can see that share
    http://www.BuyMoncler.net/

    moncler 24th September 2010 06:06permalink.

  92. Thanks for the healthy tips and info. rent villas

    Sue 24th September 2010 11:15permalink.

  93. I really enjoyed it.

    cheap mac makeup 24th September 2010 12:49permalink.

  94. This is great thanks: I've been struggling with the same problem. I ended up using Pukka on my iBook to post to different accounts, which is almost there, but as far as I can tell there's nothing similar for the Windows box I use at work. schoolgrantsblog.com