0
0
CssHow-ToBeginner · 3 min read

How to Use will-change for Performance in CSS

Use the will-change CSS property to tell the browser which properties of an element will change soon, so it can optimize rendering ahead of time. This helps improve performance for animations or transitions by reducing lag. Apply it only to elements that will change and remove it when no longer needed to avoid wasting resources.
📐

Syntax

The will-change property accepts one or more CSS property names that you expect to change soon. It can also take the value auto to reset optimizations.

  • Property names: e.g., transform, opacity, scroll-position
  • Multiple values: comma-separated list like transform, opacity
  • auto: resets any previous will-change hints
css
will-change: transform;
will-change: opacity, transform;
will-change: auto;
💻

Example

This example shows a box that will be animated using transform. The will-change property hints the browser to prepare for this change, making the animation smoother.

css
html, body {
  height: 100%;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f0f0f0;
}

.box {
  width: 100px;
  height: 100px;
  background-color: #4a90e2;
  will-change: transform;
  transition: transform 0.5s ease;
  cursor: pointer;
}

.box:hover {
  transform: translateX(150px) rotate(20deg);
}
Output
A blue square box centered on a light gray background that smoothly moves right and rotates when hovered.
⚠️

Common Pitfalls

Using will-change incorrectly can hurt performance instead of helping:

  • Overusing: Applying will-change to many elements or properties wastes memory and CPU.
  • Leaving it on permanently: Keep will-change only while the change is expected, then remove it.
  • Using vague values: Avoid using will-change: auto to try to fix performance; it resets hints instead.
css
/* Wrong: applying will-change to all elements */
* {
  will-change: transform;
}

/* Right: apply only to the element that animates */
.box {
  will-change: transform;
}
📊

Quick Reference

  • Purpose: Hint browser about upcoming changes to optimize rendering.
  • Use for: Properties like transform, opacity, scroll-position.
  • Apply only when needed: Add before animation, remove after.
  • Avoid: Overuse or applying to static elements.

Key Takeaways

Use will-change to tell the browser which CSS properties will change soon for better performance.
Apply will-change only to elements that will animate or change to avoid wasting resources.
Remove will-change after the change to prevent unnecessary memory use.
Common properties to hint are transform and opacity.
Avoid applying will-change globally or to many elements at once.