Animating display block to none

Animating elements with display set to block can be a pain in the back, as the none value is applied instantly, often requiring JavaScript or jQuery for transitions. However, there’s a simpler way using pure CSS that does the trick.

Here’s how it works

You define a keyframe animation that changes the opacity from 0 (completely transparent) to 1 (fully visible). You also control the display property within these keyframes.

In the keyframe for the starting state (e.g., 0%), you set the opacity to 0 and display to none to hide the element. In the keyframe for the ending state (e.g., 100%), you set the opacity to 1 and display to block to show the element.

When you apply this animation to an element, it smoothly transitions between hidden and visible states, without any need for JavaScript.

@keyframes fadeIn {
  0% {
    opacity: 0;
    display: none;
  }

  100% {
    opacity: 1;
    display: block;
  }
}

@keyframes fadeOut {
  0% {
    opacity: 1;
    display: block;
  }

  100% {
    opacity: 0;
    display: none;
  }
}

.element {
  animation: fadeIn 2s ease-in-out forwards;
}

.element-hidden {
  animation: fadeOut 2s ease-in-out forwards;
}

Pretty cool, right?

Read more about keyframes animation and display block-none here

Scroll to Top