Search code examples
javascriptcsscss-transitions

CSS Transition doesn't work with top, bottom, left, right


I have an element with style

position: relative;
transition: all 2s ease 0s;

Then I want to change its position smoothly after clicking on it, but when I add the style change the transition doesn't take place, instead, the element moves instantly.

$$('.omre')[0].on('click',function(){
    $$(this).style({top:'200px'});
});

However, if I change the color property, for example, it changes smoothly.

$$('.omre')[0].on('click',function(){
    $$(this).style({color:'red'});
});

What might be the cause of this? Are there properties that aren't 'transitional'?

EDIT: I guess I should have mentioned that this is not jQuery, it's another library. The code appears to work as intended, styles are being added, but transition only works in the second case?


Solution

  • Try setting a default value for top in the CSS to let it know where you want it to start out before transitioning:

    CSS

    position: relative;
    transition: top 2s ease 0s; /* only transition top property */
    top: 0; /* start transitioning from position '0' instead of 'auto' */
    

    The reason this is needed is because you can't transition from a keyword, and the default value for top is auto.

    It is also good practice to specify exactly what you want to transition (only top instead of all) both for performance reasons and so you don't transition something else (like color) unintentionally.