htmlcsscss-animationsweb-frontendweb-animations

How to loop through a CSS Animation?


I'm learning how to do animations in CSS. I know I can set the iteration-count property to infinite and it will run indefinitely, but I want the loop to be smooth. After coming back to 0% in the keyframe the animation is not smooth and changes to that property instantly. I want the transition from 100% to 0% to be smooth if that makes sense.

This is my HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>CSS Animations</title>
</head>
<body>
    <div id="shape"></div>
</body>
</html>

This is my CSS

*
{
    margin:0px;
    padding:0px;
}
body
{
    display: flex;
    justify-content: center;
    align-items: center;
    height:100vh;
}
#shape
{
    background-color: red;
    width:100px;
    height:100px;
    border-radius:50%;
    border:0px;
    animation-name:color-function;
    animation-duration: 5s;
    animation-timing-function: linear;
    animation-iteration-count: infinite;
    animation-fill-mode: forwards;
}
@keyframes color-function
{
    0%
    {
        background-color: red;
        height:100px;
        border-radius: 50%;
    }
    25%
    {
        background-color: yellow;
        height:100px;
        border-radius: 50%;
    }
    50%
    {
        background-color: blue;
        height:100px;
        border-radius: 50%;
    }
    75%
    {
        background-color: green;
        height:100px;
        border-radius: 50%;
    }
    100%
    {
        background-color: red;
        height:150px;
        border-radius: 0%;
    }
}

Thank you


Solution

  • If you want to make the Transition smooth, then obviously you should make the ending equal to the beginning.

    Then, there is no difference between the beginning and ending.

    I made my own version of your CSS code to show you how I would have done it. You should modify it to make your own version.

    
    @keyframes color-function
    {
        0%
        {
            background-color: red;
            height:100px;
            border-radius: 50%;
        }
        20%
        {
            background-color: yellow;
            height:100px;
            border-radius: 50%;
        }
        40%
        {
            background-color: blue;
            height:100px;
            border-radius: 50%;
        }
        60%
        {
            background-color: green;
            height:100px;
            border-radius: 50%;
        }
        80%
        {
            background-color: red;
            height:150px;
            border-radius: 0%;
        }
        100%
        {
            background-color: red;
            height:100px;
            border-radius: 50%;
        }
    }