Skip to content

Instantly share code, notes, and snippets.

@bigsergey
Last active May 13, 2016 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bigsergey/6779fee24494a0f6b2241821d16b2348 to your computer and use it in GitHub Desktop.
Save bigsergey/6779fee24494a0f6b2241821d16b2348 to your computer and use it in GitHub Desktop.

CSS Animations

How it works:

image

Source: Rendering: repaint, reflow/relayout, restyle

Define css animation:

@keyframes myAnimation {
  0% {
    opacity: 0;
    transform: translate(0, 0);
  }
  30% {
    opacity: 1;
    transform: translate(0, 0);
  }
  60% {
    transform: translate(100px, 0);
  }
  100% {
    transform: translate(100px, 100px);
  }
}
#box {
   animation: myAnimation 2.75s;
}

TIPS

Be careful of animating properties that change the dimensions of or position of objects on your page (also known as causing a reflow). These can be especially slow, depending on the browser.

  • top
  • left
  • right
  • bottom
  • margin-*

Instead use the transform property and the translate(), translateX(), and translateY() function.

Code examples

Bad:

function test() {
var e = $('#test');
var width = e.css('width');
if (width == '50px')
e.css('width', '100px');
 
var height = e.css('height');
if (height == '50px')
e.css('height', '100px');
}

e.css() fires window.getComputedStyle() and then reflow.

Good:

function test() {
var e = $('#test');
var width = e.css('width'),
height = e.css('height');
 
if (width == '50px')
e.css('width', '100px');
 
if (height == '50px')
e.css('height', '100px');
}

First read values then set new values.

Useful links:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment