Jump to content
GreenSock

GreenSock Docs

CSSRulePlugin

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:

  1. .myClass {
  2. color:#FF0000;
  3. }
  4. .myClass:before {
  5. content:"This content is before.";
  6. color:#00FF00;
  7. }

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:

  1. var rule = CSSRulePlugin.getRule(".myClass::before"); //get the rule
  2. 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:

  1. 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.

Methods

getRule( selector:String ) : Object

[static] Provides a simple way to find the style sheet object associated with a particular selector like ".myClass" or "#myID".

Copyright 2017, GreenSock. All rights reserved. This work is subject to theterms of useor for Club GreenSock members, the software agreement that was issued with the membership.
×