CSS Will Change
The will-change CSS property hints to browsers how an element is expected to change. Browsers can set up optimizations before an element is actually changed. These kinds of optimizations can increase the responsiveness of a page by doing potentially expensive work before they are actually required.
1. Syntax
will-change: auto;
will-change: scroll-position;
will-change: contents;
will-change: transform; /* Example of <custom-ident> */
will-change: opacity, transform;
2. Values
auto: The browser performs optimizations as it normally would.scroll-position: Indicates that the author expects to animate or change the scroll position of the element in the near future.contents: Indicates that the author expects to animate or change something about the element's contents in the near future.<custom-ident>: Indicates that the author expects to animate or change the property with the given name on the element in the near future. Common values aretransform,opacity,left,top, etc.
3. Usage
Use will-change sparingly. It consumes resources (like memory) to prepare for changes.
.sidebar {
will-change: transform;
}
This tells the browser to promote the element to its own layer (compositor layer), similar to the old transform: translateZ(0) hack, but semantically correct.
4. Best Practices
- Don't apply it to everything: Overuse can cause the browser to consume excessive memory and actually hurt performance.
- Use it as a last resort: Try to fix performance issues with standard optimizations first.
- Remove it when done: Ideally, apply it via JavaScript right before the change happens and remove it after.
const element = document.getElementById('element');
// When hover starts
element.addEventListener('mouseenter', () => {
element.style.willChange = 'transform';
});
// When animation ends
element.addEventListener('transitionend', () => {
element.style.willChange = 'auto';
});
programming/css/css programming/css/transitions-and-animations programming/javascript/vanilla/performance-api