How to hide a div after 5 seconds in CSS?

With CSS, it is quite easy to hide a div element after 5 seconds or any other time period.

To do this, we have to take help of the animation property. To set an animation, we have to first define a keyframe rule, which decides what to do with the element during different points of animation.

In our case, we want the div element to be visible for 5 seconds and after that is should be hidden. Once the keyframe is defined, we can use it with the animation property which will be played for 5 seconds.

To show and hide the div we are using the opacity property. An opacity:1; means fully visible and opacity:0; means completely hidden.

Here is a working example of it:

Example:

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

Here, we have defined a keyframe named ‘hideMe’, which keeps the div visible until the animation is reached 99.99%. As soon as the animation reaches 99.99% or in other words 5 seconds completes, the div element becomes hidden.


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.

    View all posts