Search code examples
htmlcssstylesheettransform

How to play CSS3 transitions in a loop?


The following style is just an example of how to set transitions in CSS3.
Is there a pure CSS trick to make this play in loop?

div {
    width:100px;
    height:100px;
    background:red;
    transition:width 0.1s;
    -webkit-transition:width 0.1s; /* Safari and Chrome */
    -moz-transition:width 0.1s; /* Firefox 4 */
    -o-transition:width 0.1s; /* Opera */
    transition:width 0.1s; /* Opera */
}

div:hover {
    width:300px;
}

Solution

  • CSS transitions only animate from one set of styles to another; what you're looking for is CSS animations.

    You need to define the animation keyframes and apply it to the element:

    @keyframes changewidth {
      from {
        width: 100px;
      }
    
      to {
        width: 300px;
      }
    }
    
    div {
      animation-duration: 0.1s;
      animation-name: changewidth;
      animation-iteration-count: infinite;
      animation-direction: alternate;
    }
    

    Check out the link above to figure out how to customize it to your liking, and you'll have to add browser prefixes.