Dec 19, 2014

From jQuery Animate to Css Transitions

blogpost cover image
With CSS3 we have got ability to move some of animations on our website from javascript to CSS. It can be achieved by using transitions. In this post I will describe basic usage of them.

As example I will use code from my last post, menu item highlight on hover effect. But instead of calling jQuery animate I will make transition. First little reminder, structure from my last post with corresponding css and js code:

<iframe width="100%" height="300" src="//" allowfullscreen="allowfullscreen" frameborder="0"></iframe>

basic CSS:

    list-style: none;
    padding-left: 0;

    height: 20px;
    background: gray;
    display: inline-block;
    margin-bottom: 5px;
    padding: 3px 6px;
    color: white;

Javascript part:

  $('#example1 li').mouseover(function(e){
    $({opacity: .5}, 400)
    $({opacity: 1}, 400)

CSS transitions

Along with many new features of CSS3 we have transitions. They are simply CSS properties we can define for our elements. Transitions modify the way of displaying dynamic css changes of our elements. So for example if we want to change our element background from green to red, we can decide how long it will take to move from one state to another and create smooth animation just using CSS. Basic syntax looks like this:

css transition example:

  transition: opacity 1s;

First we define property for which we want to apply transition and then duration for it. We can specify more than one transition, just separating them with comma.

css transition example:

    transition: opacity 1s, width 1s;

We can also use ‘all’ as transition property which means all allowed properties will be animated on change. The same result is obtained with no property specified. Now let’s back to our example. To replace jQuery animate we just need to add ‘transition: opacity 1s;’ to our li element. The result is presented below

<iframe width="100%" height="300" src="//" allowfullscreen="allowfullscreen" frameborder="0"></iframe>

And that’s it! Just one line in CSS. Using transitions we can create very nice animations for our website without including any external javascript libraries. However javascript have much more events on which we can react and more control for animations. So after all, I wanted to show alternative for for jQuery animate method. Now it’s your call to choose solution most suitable for Your problem.