How to play CSS3 transitions in a loop?

HtmlCssStylesheetTransform

Html Problem Overview


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;
}

Html Solutions


Solution 1 - Html

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.

Solution 2 - Html

If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:

@keyframes changewidth {
  from {
    transform: scaleX(1);
  }

  to {
    transform: scaleX(2);
  }
}

div {
  animation-duration: 0.1s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1327073View Question on Stackoverflow
Solution 1 - HtmlfreejoshView Answer on Stackoverflow
Solution 2 - HtmlLucasView Answer on Stackoverflow