Search code examples
cssreactjsanimation

CSS Keyframe animation resets the transform value set prior to the animation


Was working on an animation on a square rotated 45 deg to make a diamond. the animation simply is meant to scale the diamond out however I noticed that every time the animation started, the transform value I had set transform: rotate(45deg) is reset before the animation runs and because of this I have to run the rotate function again during the animation. is there away I can run the animation which scales the diamond, without it reseting the initial transform value? I am using Material UI components.

       <Box
        sx={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          width: "10vh",
          height: "10vh",
          border: "1px solid",
          borderColor: "tertiary.main",
          transform: "rotate(45deg)",
          animation: "expand 500ms linear forwards",
          animationDelay: "2s",
          "@keyframes expand": {
            "0%": {
              transform: "scale(1)",
            },
            "100%": {
              transform: "rotate(45deg) scale(12)",
            },
          },
        }}
      >
      
      </Box>

Solution

  • So in css animation each keyframe sets a full transformation - which means any previous transformations are reset. Just include rotate(45deg) in both the first and last keyframes:

    "@keyframes expand": {
      "0%": {
        transform: "rotate(45deg) scale(1)",
      },
      "100%": {
        transform: "rotate(45deg) scale(12)",
      },
    },