Home >Web Front-end >CSS Tutorial >How Can I Create Smooth CSS Gradient Animations Without Abrupt Position Changes?

How Can I Create Smooth CSS Gradient Animations Without Abrupt Position Changes?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-12 22:01:14474browse

How Can I Create Smooth CSS Gradient Animations Without Abrupt Position Changes?

Animating Gradients Using CSS

Certain scenarios can present difficulties in achieving seamless gradient animations. One notable issue is the abrupt position changes during the animation. The provided code demonstrates this problem:

.animated {
  animation: gra 5s infinite;
  animation-direction: reverse;
}

@keyframes gra {
  0% {
    background: linear-gradient(135deg, #ff670f 0%, #ff670f 21%, #ffffff 56%, #0eea57 88%);
  }
  50% {
    background: linear-gradient(135deg, #ff670f 0%, #ff670f 10%, #ffffff 40%, #0eea57 60%);
  }
  100% {
    background: linear-gradient(135deg, #ff670f 0%, #ff670f 5%, #ffffff 10%, #0eea57 40%);
  }
}

Solution

To resolve this issue, you can utilize CSS's background-position property in conjunction with keyframes to create a smoother animation. Consider the following code:

#gradient
{
    background: linear-gradient(130deg, #ff7e00, #ffffff, #5cff00);
    background-size: 200% 200%;

    -webkit-animation: Animation 5s ease infinite;
    -moz-animation: Animation 5s ease infinite;
    animation: Animation 5s ease infinite;
}

@-webkit-keyframes Animation {
    0%{background-position:10% 0%}
    50%{background-position:91% 100%}
    100%{background-position:10% 0%}
}
@-moz-keyframes Animation {
    0%{background-position:10% 0%}
    50%{background-position:91% 100%}
    100%{background-position:10% 0%}
}
@keyframes Animation { 
    0%{background-position:10% 0%}
    50%{background-position:91% 100%}
    100%{background-position:10% 0%}
}

In this code:

  • The background-size property ensures the gradient's seamless looping.
  • The background-position property controls the starting position of the gradient.
  • The keyframes animate the background-position property, creating the illusion of gradient movement.

The above is the detailed content of How Can I Create Smooth CSS Gradient Animations Without Abrupt Position Changes?. 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