0

I recently got asked which of these snippets was more performant in a code test for a job. Which is correct and why?

/* Option 1 */
.nav {
  left: -250px;
  transition: left 300ms linear;
}

.nav--open {
  left: 0px;
  transition: left 300ms linear;
}

/* Option 2 */
.nav {
  transform: translateX(-250px);
  transition: transform 300ms linear;
}

.nav--open {
  transform: none;
  transition: transform 300ms linear;
}

blackhaj
  • 313
  • 2
  • 10

1 Answers1

1

It has to do with frame rates. Animating the left property triggers layout which might lead to skipped frames. Transforms are better to animate because they do not trigger layout or paints and can be hardware accelerated.

To achieve a silky smooth 60fps in your CSS animations, you want to limit, as much as you can, your animations to the properties opacity, translate, rotate and scale. You should always look to avoid animating properties that will trigger layout or paints, both of which are expensive and may lead to skipped frames.

Have a look at this article by Paul Lewis and Paul Irish, written in 2013 but relevant to date - https://www.html5rocks.com/en/tutorials/speed/high-performance-animations/

Kingsley
  • 777
  • 1
  • 12
  • 35