Mastodon hachyterm.io

Have you ever wanted to gradually float a toast message into your screen?

One way to do this is by adding an animation effect, and a fade-in/fade-out transition is just the thing I needed.

In this article, I want to show you how to create a smooth fade-in/fade-out effect using CSS, with a faster fade-in time and a slower fade-out time.

To create this effect, we can use the following code:

.fade-in-out {
  opacity: 0;
  animation: fade-in 1s ease-in forwards, fade-out 4s 1s ease-out forwards;
}

@keyframes fade-in {
  100% {
    opacity: 1;
  }
}

@keyframes fade-out {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

Here’s how it works: we start by defining a class called “fade-in-out” and apply it to the element we want to animate. We set the initial opacity to 0 to make the element invisible.

Next, we define two keyframe animations: “fade-in” and “fade-out”. The “fade-in” animation gradually increases the opacity of the element from 0 to 1, while the “fade-out” animation gradually decreases the opacity from 1 to 0.

The “fade-in” animation has a single keyframe at 100% that sets the opacity to 1. It runs for 1 second and uses the “ease-in” timing function to start slowly and speed up.

The “fade-out” animation has two keyframes: one at 0% and one at 100%. The first keyframe sets the opacity to 1, so the element is fully visible at the start of the animation. The second keyframe sets the opacity to 0, so the element is fully invisible at the end. This animation runs for 4 seconds and uses the “ease-out” timing function, which means it starts quickly and slows down.

Finally, we apply both animations to the “fade-in-out” class using the “animation” property. The “forwards” keyword means that the final state of the animation will be retained after it’s finished.

To use this effect, simply apply the “fade-in-out” class to the element you want to animate. You can customize the duration and timing functions of the animations to create different effects.