Home >Web Front-end >CSS Tutorial >How to Create an Endless CSS Rotation Animation for Loading Icons?

How to Create an Endless CSS Rotation Animation for Loading Icons?

Barbara Streisand
Barbara StreisandOriginal
2024-11-09 10:11:02669browse

How to Create an Endless CSS Rotation Animation for Loading Icons?

Endless CSS Rotation Animation

Loading icons are essential for user experience, providing visual feedback during website loading. Customizing the rotation of these icons using CSS can enhance their functionality and aesthetics. However, implementing infinite rotation with CSS can prove challenging.

Consider the following example:

#test {
    width: 32px;
    height: 32px;
    background: url('refresh.png');
}

.rotating {
    -webkit-transform: rotate(360deg);
    -webkit-transition-duration: 1s;
    -webkit-transition-delay: now;
    -webkit-animation-timing-function: linear;
    -webkit-animation-iteration-count: infinite;
}
<div id='test' class='rotating'></div>

While this CSS appears intuitive, it fails to produce the intended infinite rotation for the loading icon. To achieve endless rotation, the animation must be applied using keyframes instead of transformations.

The corrected CSS using keyframes follows:

@-webkit-keyframes rotating /* Safari and Chrome */ {
  from {
    -webkit-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(360deg);
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
@keyframes rotating {
  from {
    -ms-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -webkit-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  to {
    -ms-transform: rotate(360deg);
    -moz-transform: rotate(360deg);
    -webkit-transform: rotate(360deg);
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

.rotating {
  -webkit-animation: rotating 2s linear infinite;
  -moz-animation: rotating 2s linear infinite;
  -ms-animation: rotating 2s linear infinite;
  -o-animation: rotating 2s linear infinite;
  animation: rotating 2s linear infinite;
}

This corrected code ensures smooth and continuous rotation of the loading icon indefinitely, enhancing its functionality and visual appeal.

The above is the detailed content of How to Create an Endless CSS Rotation Animation for Loading Icons?. 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