Home >Web Front-end >CSS Tutorial >How can you create a sliding animation in CSS when the animated element has `display: none;`?

How can you create a sliding animation in CSS when the animated element has `display: none;`?

Barbara Streisand
Barbara StreisandOriginal
2024-11-15 18:51:02672browse

How can you create a sliding animation in CSS when the animated element has `display: none;`?

CSS Animation in Conjunction with Display: None

You desire to create a CSS animation where a "main-div" slides in after a specified duration, pushing down other divs in its path. However, setting the "display" property to "none" for the "main-div" prevents the animation from triggering.

To overcome this limitation, you cannot directly animate between "display: none;" and "display: block;" or between "height: 0;" and "height: auto." Instead, you must manually specify the height of the div.

Here's an example using vanilla CSS:

#main-image {
    height: 0;
    overflow: hidden;
   -moz-animation-delay: 3.5s;
   -webkit-animation-delay: 3.5s;
   -o-animation-delay: 3.5s;
    animation-delay: 3.5s;
}

@-prefix-keyframes slide {
  from {height: 0;}
  to {height: 300px;}
}

In this code, we explicitly set the height of the "main-image" div to 0 pixels initially, effectively hiding it. The "overflow: hidden;" property prevents any content from overflowing the specified height.

Then, we use CSS animations to smoothly transition from the initial height of 0 to the desired height of 300px. The "animation-delay" property ensures that the animation starts after a 3.5-second delay.

Using this approach, you can create a sliding animation without using "display: none;" while maintaining the smooth transition and precise timing that CSS provides.

The above is the detailed content of How can you create a sliding animation in CSS when the animated element has `display: none;`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn