Animating from “display: block” to “display: none”

As you might already know, CSS3 transitions and animations allow you to animate a specific set of CSS properties. One of the properties that cannot be animated is the display property.

It would be great if we could do it, but it’s not currently possible and I’m guessing it never will be (e.g. how would you animate to “display: table”?). But there are ways to work around it, and I’ll present one way here.

Why the Need to Animate “display”?

The need to animate the display property comes from wanting to solve the following problem:

  • You want to make an element gradually disappear visually from the page.
  • You don’t want that element to take up space after it has disappeared (i.e., you want the disappearance to cause reflow).
  • You want to use CSS for the animation, not a library.

For this reason, animating opacity to zero is simply not enough because an element with zero opacity still occupies the same space on the page.

Let’s look at how we might attempt to solve this problem, step by step.