Jump to content
Search Community

CSS variable as property value

Overthane test
Moderator Tag

Go to solution Solved by OSUblake,

Recommended Posts

Hi y'all, I'm trying to animate something by using the value stored inside a CSS variable as a value of the `height` property in `GSAP.to`.

 

I'm aware that you can reassign value to CSS variables as part of a GSAP animation (not sure the correct term for that, just seen it in a few posts).

 

Please see my minimal example in the CodePen.

 

The square/rectangle is my attempt at using the variable as a value, and as you can see no animation occurs. The circle is using plain pixels animation, which works as expected. 

 

I'm currently using the latest Chrome browser, on MacOS Catalina.

 

Thanks in advance!

See the Pen KKmGRPZ by overthane (@overthane) on CodePen

Link to comment
Share on other sites

Hi @Overthane


Here you have an example of what you want to do:

See the Pen ae4d38d4fb3db8526a15111df7cea562 by nicofonseca (@nicofonseca) on CodePen



In order to improve animations with CSS variables, I recommend you to use the variables inside the scope of the element you want to animate and not global variables, because they can bring some performance issues.
Also, on the CSS you can use calc(var(my-variable) * 1px) or calc(var(my-variable) * 1deg) or whatever you want to animate.
Lastly, if possible it is better to animate transform (rotate, scale, y, x) properties instead or width/height.

Hope this helps!

Cheers,
Nico.

  • Like 5
Link to comment
Share on other sites

@OSUblake @nicofonseca

 

Thank you for the speedy and thorough replies!

 

I get what you guys mean, but what I really wanted to do was use the value that is already stored in a css variable to animate a property to that value. 

 

But thinking about it I guess it really must not be worth the effort, as I would probably have to track changes to that variable anyway in JS (I think?). There's probably a good reason that this doesn't run as I'm envisioning! haha

 

Thanks again, and happy Friday all!

Link to comment
Share on other sites

16 minutes ago, Overthane said:

I get what you guys mean, but what I really wanted to do was use the value that is already stored in a css variable to animate a property to that value. 

 

Then you would have to get that value. "var(--height)" is just a string and has no meaning to GSAP.

 

gsap.to(document.getElementById("rect"), {
  duration: 2,
  height: (i, el) => getComputedStyle(el).getPropertyValue('--height'),
  yoyo: true,
  repeat: -1
});

 

  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...