Need help in this animation

JS Fiddle: https://jsfiddle.net/e9o4x13s/

I am trying to achieve an effect in which the square expands from 0 to 300 width and them to 0 again but the direction of the latter should happen from left to right instead of right to left which happens in the demo.

.square {
	width: 300px;
	height: 300px;
	background-color: #345;
	animation: reveal 2s forwards;
}

@keyframes reveal {
	0% {
		width: 0;
	}
	50% {
		width: 300px;
	}
	100% {
		width: 0;
	}
}
<div class="square"></div>

One way would be to use absolute positioning. But possibly better would be to use a transform (scale) to do the animation and adjust the transform-origin to suit.

 
 
…and here is another possible way …

<!DOCTYPE HTML>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>untitled document</title>

<link rel="stylesheet" href="screen.css" media="screen">

<style media="screen">
body {
    background-color: #f0f0f0;
    font: 1em/150% verdana, arial, helvetica, sans-serif;
 }
.square {
    width: 18.75em;
    height: 18.75em;
    background-color: #345;
    animation: reveal 2s forwards;
 }

@keyframes reveal {
    0%   {
          width: 0;
         }
    50%  {
	  width: 18.75em;
          margin-left: 0;
         }
    100% {
          width: 0;
          margin-left: 18.75em;
         }
 }
</style>

</head>
<body> 

 <div class="square"></div>

</body>
</html>

coothead

1 Like

I’d probably go with coothead’s example but just for fun here’s another method :slight_smile:

https://codepen.io/paulobrien/full/jGWWNY/

Animations are always smoother with translate rather than using margin, width or positioning.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.