How to show and hide a div with transition in CSS?

Hide
Show

In modern websites, we often need to show and hide a div or any other element based on user interaction. But, showing or hiding any element instantly doesn’t make a good impact on visitors’ overall experience. It may be a popup, button, or any other element.

So instead of showing or hiding instantly, we show or hide the element with a transition. In other words, the element should be gradually visible or hidden.

In CSS, to show and hide a div with transition, we use the animation property along with the opacity property.

Here is a working example to hide the div with a transition:

Example:

div{
    width: 250px;
    height: 100px;
    background: yellow;
    border: 2px dashed blue;
    font-size: 20px;
    text-align: center;
    animation: hideMe 2s forwards;
}
@keyframes hideMe{
    0%{
        opacity: 1;
    }
    100%{
        opacity: 0;
    }
}

Explanation:

To define an animation the very first thing we need is a keyframe rule. A keyframe rule specifies what to do with the element at different points during the animation. Therefore, we have defined a keyframe rule named ‘hideMe’.

In our example, at the starting we want the div to become fully visible. Therefore, at 0%, we have put opacity:1;. At the end of the animation, we want the div to become completely hidden therefore, at 100%, we have put opacity:0;.

Once this keyframe is defined, we can use it with the animation property.

Note: If you want the animation to play again and again, you can replace forwards with infinite.


Show the div with a transition

In the last example, we learned how to hide a div with the transition. In the similar way, we can show a div with transition.

Here, we want the div element to be hidden at the beginning and then become gradually visible. To do that, we have to just reverse the keyframe.

Now at the beginning, we want the div to become fully hidden, therefore at 0% we have to put opacity:0; and at 100% we have to put opacity:1;.

Here is a working example to show the div with a transition:

Example:

div{
    width: 250px;
    height: 100px;
    background: yellow;
    border: 2px dashed blue;
    font-size: 20px;
    text-align: center;
    opacity: 0;
    animation: showMe 3s forwards;
}
@keyframes showMe{
    0%{
        opacity: 0;
    }
    100%{
        opacity: 1;
    }
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.