0

I am trying to hide a div with an animation on some action. My initial pass at it looked as follows:

.row {
  height: 50px;
  transition: height 200ms ease-in-out;
  &.hidden {
    height: 0;
  }
}

Where my DOM structure was as follows (with react):

<div className={styles.container}>
  <div className={styles.row} />
  <div className={classnames(styles.row, { [styles.hidden]: !this.state.active })}
</div>

While this did work, it was very slow. I have heard that transforms are efficient to transition in CSS, so I decided to try the following instead.

.row {
  height: 50px;
  transform-origin: top;
  transition: transform 200ms ease-in-out;

  &.hidden {
    transform: scaleY(0);
  }
}

However, within the container, the second row is still displaying as a 50px box, but the inspector says that it has 0 height.

How can this transform be correctly applied to hide the second box?

corvid
  • 10,733
  • 11
  • 61
  • 130

1 Answers1

1

3D transforms are efficient because the browser will composite the targeted elements into their own layers and offload the animations to the GPU. height and even scaleY() are not 3D transformations and do not benefit from GPU acceleration (the CPU still handles it).

To go back to your example with height, you can force the browser to use GPU acceleration by tricking it with a fake transform property like transform: translateZ(0); (translateZ() is the 3D component of translate3d(), much like scaleZ() is the 3D component of scale3d()).

Here's a quick demo:

document.querySelector('button').addEventListener('click', function() {
  document.querySelector('.row').classList.toggle('hidden');
});
.row {
  background-color: green;
  height: 50px;
  overflow: hidden;
  transition: height 200ms ease-in-out;
  transform: translateZ(0); /* or translate3d(0,0,0), rotateZ(360deg), etc. */
}

.row.hidden {
  height: 0;
}

button {
  left: 0;
  position: absolute;
  top: 100px;
}
<div class="row">Some text</div>

<button>Toggle Row Visibility</button>

With the added property, the browser should utilize GPU acceleration, significantly improving the animation. See this question for more information related to transforms and GPU acceleration.

I would recommend trying this first to see if it speeds up the animation enough in your app. You could alternatively try adding the will-change property though this is part of a working draft and currently non-standard.

Community
  • 1
  • 1
skyline3000
  • 7,639
  • 2
  • 24
  • 33