Description
Allows GSAP to animate the raw style sheet rules which affect all objects of a particular selector rather than affecting an individual DOM element’s style (that’s what the CSSPlugin is for).
For example, if you have a CSS class named myClass
that sets background-color
to #FF0000
, you could tween that to a different color and all of the objects on the page that have a class of myClass
would have their background color change. Typically it is best to use the regular CSSPlugin to animate CSS-related properties of individual elements so that you can get very precise control over each object, but sometimes it can be useful to tween the global rules themselves instead. For example, pseudo elements (like ::after
, ::before
, etc. are impossible to reference directly in JavaScript, but you can animate them using CSSRulePlugin.
The plugin itself actually has a static getRule()
method that you can use to grab a reference to the style sheet itself based on the selector you used in your CSS.
For example, let’s say you have CSS like this:
.myClass {
color:#FF0000;
}
.myClass:before {
content:"This content is before.";
color:#00FF00;
}
Now let’s say you want to tween the color of the .myClass:before to blue. Make sure you load the CSSRulePlugin and CSSPlugin JavaScript files and then you can do this:
var rule = CSSRulePlugin.getRule(".myClass::before"); //get the rule
gsap.to(rule, {duration: 3, cssRule: {color: "blue"}});
And if you want to get all of the ::before
pseudo elements, the getRule()
will return an array of them, so I could do this:
gsap.to( CSSRulePlugin.getRule("::before"), {duration: 3, cssRule: {color: "blue"}});>
Keep in mind that it is typically best to tween a property that has already been defined in the specific rule that you’re selecting because it cannot perform a calculated style (the combination of styles from other selectors that might pertain to similar elements). For example, if we didn’t define any color initially for the .myClass::before
and tried to tween its color to blue, it would start from transparent
and go to blue
. One way around this is to simply set your starting values explicitly in the tween by doing a fromTo()
. That way there’s no having to guess what the starting value should be when it isn’t defined previously.
Don’t forget to wrap the values in a cssRule: {}
object.
Styles defined inside media queries may not be accessible or tweenable.