Capítulo 162 de 411

Chapter 162: Animating backgroundSize "cover"/"contain" (Helper)

Core Idea

A helper that converts a keyword backgroundSize value like "cover" or "contain" into its equivalent pixel dimensions for the current element, because GSAP can only tween between numeric values, not CSS keywords.

Key Concepts

  • Reads the element's computed backgroundImage/backgroundSize and, if a native width/height isn't supplied, loads the image to detect its natural size.
  • Accepts an optional config with size (target size/keyword to convert), nativeWidth, nativeHeight — supplying the native dimensions avoids an extra image load.
  • Returns the size already converted to a px-based string that GSAP can tween normally.

Code Examples

// simple: returns current backgroundSize in px
bgSize(".class");

// advanced: converts "cover" to px assuming a known native image size
bgSize(".class", { size: "cover", nativeWidth: 600, nativeHeight: 400 });
  • What it demonstrates: bridging a non-numeric CSS keyword into a tweenable pixel value.

Key Takeaways

  1. Supplying nativeWidth/nativeHeight avoids a potentially slow extra image load to detect natural size.
  2. Only needed because backgroundSize keywords aren't numeric — plain px/percentage values tween directly without this helper.

Connects To

  • CSS plugin (core): handles the actual tween once the size is converted to a number.