CSS `will-change` 완전 이해하기: 언제 쓰고, 어떻게 써야 할까?

웹 애니메이션이나 인터랙션을 만들다 보면 “이 요소가 더 부드럽게 움직였으면 좋겠다”는 생각이 들 때가 있습니다. 이때 한 번쯤 보게 되는 CSS 속성이 바로 will-change입니다.
이 속성은 이름만 보면 뭔가 대단한 성능 최적화 옵션처럼 느껴지지만, 실제로는 꽤 조심해서 써야 하는 “브라우저에게 주는 힌트”에 가깝습니다. 잘 쓰면 도움이 될 수 있지만, 무분별하게 쓰면 오히려 성능이 나빠질 수도 있습니다.
이번 글에서는 will-change가 정확히 무엇인지, 왜 존재하는지, 언제 써야 하는지, 그리고 실제로 어떻게 사용하는지를 차근차근 정리해보겠습니다.
will-change란?
will-change는 요소에 어떤 변화가 곧 일어날 것이라고 브라우저에 미리 알려주는 CSS 속성입니다.
즉, 개발자가 브라우저에게 이렇게 말하는 셈입니다.
“이 요소는 곧 transform이나 opacity 같은 속성이 바뀔 예정이니, 미리 준비해 둬.”
브라우저는 이 힌트를 바탕으로 렌더링 최적화를 미리 수행할 수 있고, 경우에 따라 애니메이션이나 전환이 더 부드럽게 동작할 수 있습니다.
기본 예시는 아주 단순합니다.
.box {
will-change: transform;
}
위 코드는 .box 요소의 transform 값이 곧 바뀔 수 있으니 브라우저가 사전 준비를 하도록 힌트를 주는 코드입니다.
왜 필요한가?
브라우저는 화면을 그릴 때 단순히 HTML과 CSS를 한 번에 처리하는 것이 아니라, 여러 단계를 거쳐 렌더링합니다. 어떤 속성이 바뀌느냐에 따라 다시 레이아웃을 계산하거나, 다시 페인트를 하거나, 합성 단계만 다시 수행할 수도 있습니다.
이때 transform이나 opacity처럼 비교적 효율적으로 처리할 수 있는 속성이 자주 바뀌는 경우, 브라우저가 미리 준비해두면 애니메이션이 더 자연스럽게 보일 가능성이 있습니다.
즉, will-change는 성능을 직접 높여주는 마법 같은 속성이 아니라, 브라우저가 더 나은 최적화를 할 수 있도록 사전 정보를 제공하는 역할을 합니다.
자주 사용하는 값
will-change에는 보통 다음과 같은 값이 들어갑니다.
1. transform
요소의 이동, 회전, 확대/축소 같은 변형이 일어날 때 사용합니다.
.card {
will-change: transform;
}
2. opacity
투명도 변화가 예정되어 있을 때 사용합니다.
.modal {
will-change: opacity;
}
3. 여러 값 함께 사용
.panel {
will-change: transform, opacity;
}
슬라이드되면서 동시에 페이드 효과가 들어가는 UI에서 자주 볼 수 있는 형태입니다.
4. auto
기본값입니다. 특별한 최적화 힌트를 주지 않는 일반 상태라고 보면 됩니다.
.element {
will-change: auto;
}
실제 사용 예제
가장 이해하기 쉬운 예시는 버튼을 눌렀을 때 박스가 옆으로 이동하는 경우입니다.
HTML
<div class="box"></div>
<button id="moveBtn">Move</button>
CSS
.box {
width: 120px;
height: 120px;
background: royalblue;
transition: transform 0.4s ease;
}
.box.animate {
will-change: transform;
transform: translateX(200px);
}
JavaScript
const box = document.querySelector('.box');
const button = document.querySelector('#moveBtn');
button.addEventListener('click', () => {
box.classList.add('animate');
box.addEventListener(
'transitionend',
() => {
box.style.willChange = 'auto';
},
{ once: true }
);
});
이 예제는 어떻게 동작할까?
버튼을 클릭하면 .box에 animate 클래스가 추가되고, transform: translateX(200px)가 적용되면서 요소가 오른쪽으로 이동합니다.
이때 will-change: transform이 함께 적용되어 브라우저는 해당 요소의 transform 변화에 대비할 수 있습니다. 결과적으로 상황에 따라 더 부드러운 애니메이션이 가능해집니다.
그리고 애니메이션이 끝난 뒤에는 will-change를 다시 auto로 돌려놓습니다. 이 부분이 중요합니다. will-change를 계속 유지하면 불필요한 리소스를 점유할 수 있기 때문입니다.
더 나은 사용 방식
실무에서는 will-change를 CSS에 상시 넣어두기보다, 변화가 일어나기 직전에 적용하고 끝나면 제거하는 방식이 더 낫습니다.
예를 들어 다음처럼 작성할 수 있습니다.
const box = document.querySelector('.box');
const button = document.querySelector('#moveBtn');
button.addEventListener('click', () => {
box.style.willChange = 'transform';
requestAnimationFrame(() => {
box.style.transform = 'translateX(200px)';
});
box.addEventListener(
'transitionend',
() => {
box.style.willChange = 'auto';
},
{ once: true }
);
});
이 방식이 더 좋은 이유는 분명합니다.
첫째, 정말 변화가 필요할 때만 will-change를 적용합니다.
둘째, 애니메이션이 끝나면 즉시 해제합니다.
셋째, 브라우저가 불필요하게 최적화 상태를 오래 유지하지 않도록 할 수 있습니다.
언제 사용하면 좋을까?
will-change는 모든 요소에 붙이는 속성이 아닙니다. 아래처럼 성능 민감도가 높은 인터랙션에서 제한적으로 사용하는 것이 맞습니다.
사용하기 좋은 경우
- 큰 요소에 hover 애니메이션이 들어가는 경우
- 사이드 메뉴가 슬라이드로 열리고 닫히는 경우
- 카드 드래그 인터랙션이 있는 경우
- 복잡한 UI 전환에서
transform,opacity가 자주 바뀌는 경우
예를 들어 사이드 패널이 열릴 때 다음처럼 생각할 수 있습니다.
.sidebar {
transition: transform 0.3s ease;
}
.sidebar.is-opening {
will-change: transform;
}
즉, “곧 움직일 요소”가 명확할 때만 써야 합니다.
언제 사용하면 안 될까?
이 부분이 더 중요합니다. will-change는 남용하면 오히려 성능이 나빠질 수 있습니다.
대표적으로 좋지 않은 예시는 이런 코드입니다.
* {
will-change: transform;
}
혹은 아래와 같은 코드도 위험합니다.
.card {
will-change: transform;
}
이 자체가 무조건 잘못은 아니지만, 만약 .card가 수십 개, 수백 개 존재한다면 이야기가 달라집니다. 브라우저는 많은 요소를 미리 최적화하려고 하면서 메모리를 더 많이 사용하게 되고, 결과적으로 전체 성능이 떨어질 수 있습니다.
즉, will-change는 “많이 쓸수록 좋은 옵션”이 아니라 “꼭 필요한 요소에만 잠깐 쓰는 옵션”입니다.
will-change에 대한 흔한 오해
많은 초급 개발자가 will-change를 보면 “이거 넣으면 무조건 부드러워지겠네”라고 생각합니다. 하지만 그건 사실이 아닙니다.
will-change는 다음과 같은 성격을 가집니다.
- 성능 보장 옵션이 아니다
- 브라우저 최적화를 강제하는 기능이 아니다
- 잘못 쓰면 메모리 사용량만 늘릴 수 있다
- 애니메이션 성능 문제의 근본 원인을 해결해주지 않는다
애니메이션이 끊긴다면 먼저 확인해야 할 것은 보통 다음과 같습니다.
top,left,width,height처럼 비용이 큰 속성을 애니메이션하고 있지는 않은가transform,opacity중심으로 바꿀 수 없는가- 너무 많은 DOM 요소가 동시에 움직이고 있지는 않은가
- repaint나 layout이 과도하게 발생하고 있지는 않은가
즉, will-change는 마지막 미세 조정에 가까운 도구이지, 구조적으로 잘못된 애니메이션을 구해주는 해결책은 아닙니다.
실무 기준으로 정리하면
실무에서 will-change를 볼 때는 아래 기준으로 판단하면 됩니다.
써도 되는 경우
- 곧 변화가 일어날 요소가 명확하다
transform,opacity중심의 애니메이션이다- 실제로 성능 이슈가 있거나 부드러움 개선이 필요하다
- 변화 직전에 넣고, 끝난 뒤 제거할 수 있다
피해야 하는 경우
- 특별한 이유 없이 습관처럼 넣는 경우
- 많은 요소에 한꺼번에 적용하는 경우
- 성능 측정 없이 막연히 “좋아 보이니까” 넣는 경우
- 레이아웃 변경이 큰 속성을 남발하면서
will-change로 해결하려는 경우
결론
will-change는 CSS에서 성능 최적화를 위해 존재하는 속성이지만, 그 정체는 어디까지나 브라우저에게 주는 사전 힌트입니다.
핵심은 간단합니다.
will-change는 필요한 순간에, 필요한 요소에만, 짧게 써야 합니다.
애니메이션 성능을 개선하고 싶다면 먼저 transform과 opacity를 중심으로 설계를 바꾸고, 그다음 정말 필요한 경우에만 will-change를 추가하는 편이 맞습니다.
무턱대고 전역으로 넣는 것은 최적화가 아니라 오히려 성능 낭비에 가깝습니다.
한 줄로 정리하면 이렇습니다.
will-change는 성능을 위한 힌트이지, 만능 해결책이 아닙니다.
원하시면 다음 단계로 이어서, 이 글을 더 블로그 스타일에 맞게 다듬은 버전이나, 예제 중심의 초급자용 버전으로 다시 써드리겠습니다.

When building web animations or interactions, you may sometimes think, “I wish this element moved more smoothly.” The CSS property you encounter in that situation is will-change.
Judging by its name, this property can feel like a powerful performance optimization option, but in practice it is closer to “a hint given to the browser” that needs to be used carefully. Used well, it can help. Used carelessly, it can even hurt performance.
In this article, we will go through what will-change actually is, why it exists, when to use it, and how to use it in practice.
What Is will-change?
will-change is a CSS property that tells the browser in advance that a certain change will happen soon on an element.
In other words, the developer is telling the browser something like this:
“This element is about to have a property such as transform or opacity changed, so prepare for it in advance.”
Based on this hint, the browser may perform rendering optimizations ahead of time, and in some cases animations or transitions can run more smoothly.
The basic example is very simple.
.box {
will-change: transform;
}
This code hints that the transform value of the .box element may soon change, so the browser can prepare in advance.
Why Is It Needed?
When the browser draws the screen, it does not simply process HTML and CSS all at once. It renders through multiple stages. Depending on which property changes, it may need to recalculate layout, repaint, or only rerun the compositing stage.
When properties that can be handled relatively efficiently, such as transform or opacity, change frequently, the animation may look more natural if the browser prepares for them ahead of time.
So will-change is not a magical property that directly boosts performance. It provides advance information so the browser can make better optimization decisions.
Common Values
The values commonly used with will-change are:
1. transform
Use this when transformations such as movement, rotation, scaling, or shrinking are expected.
.card {
will-change: transform;
}
2. opacity
Use this when opacity changes are expected.
.modal {
will-change: opacity;
}
3. Multiple Values Together
.panel {
will-change: transform, opacity;
}
This is often seen in UI where a panel slides while fading at the same time.
4. auto
This is the default value. You can think of it as the normal state where no special optimization hint is provided.
.element {
will-change: auto;
}
Practical Example
The easiest example to understand is a box moving sideways when a button is pressed.
HTML
<div class="box"></div>
<button id="moveBtn">Move</button>
CSS
.box {
width: 120px;
height: 120px;
background: royalblue;
transition: transform 0.4s ease;
}
.box.animate {
will-change: transform;
transform: translateX(200px);
}
JavaScript
const box = document.querySelector('.box');
const button = document.querySelector('#moveBtn');
button.addEventListener('click', () => {
box.classList.add('animate');
box.addEventListener(
'transitionend',
() => {
box.style.willChange = 'auto';
},
{ once: true }
);
});
How Does This Example Work?
When the button is clicked, the animate class is added to .box, and transform: translateX(200px) is applied, moving the element to the right.
At this moment, will-change: transform is applied together, so the browser can prepare for the element’s transform change. Depending on the situation, this can make the animation smoother.
After the animation ends, will-change is set back to auto. This part matters. If will-change stays active, it can keep occupying unnecessary resources.
A Better Usage Pattern
In real projects, it is usually better to apply will-change right before the change happens and remove it when the change finishes, rather than keeping it permanently in CSS.
For example:
const box = document.querySelector('.box');
const button = document.querySelector('#moveBtn');
button.addEventListener('click', () => {
box.style.willChange = 'transform';
requestAnimationFrame(() => {
box.style.transform = 'translateX(200px)';
});
box.addEventListener(
'transitionend',
() => {
box.style.willChange = 'auto';
},
{ once: true }
);
});
The reason this pattern is better is clear.
First, will-change is applied only when the change is really needed.
Second, it is removed immediately when the animation ends.
Third, it prevents the browser from keeping an unnecessary optimization state for too long.
When Is It Good to Use?
will-change is not a property to attach to every element. It should be used selectively in performance-sensitive interactions like the following.
Good Cases
- A large element has a hover animation
- A side menu opens and closes with a slide animation
- There is a card drag interaction
transformandopacitychange frequently in a complex UI transition
For example, when a side panel opens, you might think of it like this.
.sidebar {
transition: transform 0.3s ease;
}
.sidebar.is-opening {
will-change: transform;
}
In other words, use it only when it is clear that “this element will move soon.”
When Should You Avoid It?
This part is more important. If will-change is overused, performance can actually get worse.
A typical bad example is this:
* {
will-change: transform;
}
This kind of code is also risky:
.card {
will-change: transform;
}
This is not automatically wrong by itself. But if there are dozens or hundreds of .card elements, the story changes. The browser tries to optimize many elements ahead of time, uses more memory, and overall performance can drop.
So will-change is not “the more you use it, the better.” It is an option to use briefly and only on elements that really need it.
Common Misunderstandings About will-change
Many beginner developers see will-change and think, “If I add this, things will always become smoother.” That is not true.
will-change has these characteristics.
- It does not guarantee performance
- It does not force browser optimization
- Misuse can only increase memory usage
- It does not solve the root cause of animation performance problems
If an animation is choppy, the first things to check are usually:
- Are you animating expensive properties such as
top,left,width, orheight? - Can you switch to
transformandopacity? - Are too many DOM elements moving at the same time?
- Are repaint or layout operations happening excessively?
In other words, will-change is closer to a final fine-tuning tool. It is not a solution that saves structurally bad animations.
Practical Rule of Thumb
In real work, you can evaluate will-change with the following criteria.
Cases Where It Is Acceptable
- The element that will change soon is clear
- The animation is centered on
transformoropacity - There is an actual performance issue or a need to improve smoothness
- It can be added right before the change and removed after it ends
Cases to Avoid
- Adding it habitually without a specific reason
- Applying it to many elements at once
- Adding it vaguely because it “looks good” without measuring performance
- Trying to solve expensive layout-changing animations with
will-change
Conclusion
will-change exists in CSS for performance optimization, but its true nature is an advance hint to the browser.
The key is simple.
Use will-change only at the necessary moment, only on the necessary element, and only briefly.
If you want to improve animation performance, first design around transform and opacity, then add will-change only when it is truly needed.
Adding it globally without thought is not optimization. It is closer to wasting performance resources.
In one line:
will-change is a performance hint, not a universal solution.
If needed, this article can later be refined into a more blog-like version or rewritten as a beginner-friendly version centered on examples.

制作网页动画或交互时,有时会觉得“这个元素要是能动得更顺滑就好了”。这时经常会遇到的 CSS 属性就是 will-change。
光看名字,它像是一个很强大的性能优化选项,但实际上它更接近于“给浏览器的提示”,而且需要谨慎使用。用得好可能有帮助,滥用反而可能让性能变差。
本文会按顺序整理 will-change 到底是什么、为什么存在、什么时候应该使用,以及实际应该怎么用。
什么是 will-change?
will-change 是一个 CSS 属性,用来提前告诉浏览器某个元素即将发生某种变化。
换句话说,开发者是在对浏览器说:
“这个元素很快会改变 transform 或 opacity 这样的属性,请提前做好准备。”
浏览器可以根据这个提示预先进行渲染优化,在某些情况下动画或过渡会更顺滑。
最基本的示例非常简单。
.box {
will-change: transform;
}
这段代码是在提示浏览器,.box 元素的 transform 值可能马上会变化,可以提前准备。
为什么需要它?
浏览器绘制画面时,并不是一次性处理 HTML 和 CSS,而是经过多个渲染阶段。根据变化的属性不同,可能需要重新计算 layout、重新 paint,或者只重新执行 compositing 阶段。
如果像 transform 或 opacity 这样相对容易高效处理的属性频繁变化,浏览器提前准备后,动画看起来可能会更自然。
也就是说,will-change 不是直接提升性能的魔法属性,而是向浏览器提供预先信息,让浏览器有机会进行更好的优化。
常用值
will-change 中常见的值如下。
1. transform
当元素即将发生移动、旋转、放大或缩小等变形时使用。
.card {
will-change: transform;
}
2. opacity
当即将发生透明度变化时使用。
.modal {
will-change: opacity;
}
3. 多个值一起使用
.panel {
will-change: transform, opacity;
}
在滑动的同时加入 fade 效果的 UI 中经常会看到这种写法。
4. auto
这是默认值。可以理解为不提供特别优化提示的普通状态。
.element {
will-change: auto;
}
实际使用示例
最容易理解的例子是点击按钮时,让 box 向旁边移动。
HTML
<div class="box"></div>
<button id="moveBtn">Move</button>
CSS
.box {
width: 120px;
height: 120px;
background: royalblue;
transition: transform 0.4s ease;
}
.box.animate {
will-change: transform;
transform: translateX(200px);
}
JavaScript
const box = document.querySelector('.box');
const button = document.querySelector('#moveBtn');
button.addEventListener('click', () => {
box.classList.add('animate');
box.addEventListener(
'transitionend',
() => {
box.style.willChange = 'auto';
},
{ once: true }
);
});
这个示例如何工作?
点击按钮后,.box 会被添加 animate class,同时应用 transform: translateX(200px),元素向右移动。
此时 will-change: transform 也一起生效,浏览器可以为该元素的 transform 变化做准备。根据具体情况,这可能带来更顺滑的动画。
动画结束后,会把 will-change 重新设回 auto。这点很重要,因为如果一直保留 will-change,可能会占用不必要的资源。
更好的使用方式
在实际项目中,比起把 will-change 长期写在 CSS 里,更好的方式是在变化发生前一刻应用,并在结束后移除。
例如可以这样写。
const box = document.querySelector('.box');
const button = document.querySelector('#moveBtn');
button.addEventListener('click', () => {
box.style.willChange = 'transform';
requestAnimationFrame(() => {
box.style.transform = 'translateX(200px)';
});
box.addEventListener(
'transitionend',
() => {
box.style.willChange = 'auto';
},
{ once: true }
);
});
这种方式更好的理由很明确。
第一,只在真正需要变化时应用 will-change。
第二,动画结束后立即解除。
第三,可以避免浏览器长时间保持不必要的优化状态。
什么时候适合使用?
will-change 不是给所有元素都加的属性。应该只在下面这种对性能敏感的交互中有限使用。
适合使用的情况
- 大元素带有 hover 动画
- 侧边菜单用 slide 打开和关闭
- 有 card drag 交互
- 复杂 UI 过渡中
transform、opacity频繁变化
例如侧边面板打开时,可以这样考虑。
.sidebar {
transition: transform 0.3s ease;
}
.sidebar.is-opening {
will-change: transform;
}
也就是说,只有在“这个元素马上要移动”非常明确时才应该使用。
什么时候不应该使用?
这一点更重要。will-change 滥用时,性能反而可能变差。
典型的坏例子是这样的代码。
* {
will-change: transform;
}
下面这样的代码也有风险。
.card {
will-change: transform;
}
这本身并不一定错误。但如果 .card 有几十个、几百个,情况就不同了。浏览器会试图预先优化大量元素,使用更多内存,最终可能让整体性能下降。
因此,will-change 不是“用得越多越好”的选项,而是“只在真正必要的元素上短时间使用”的选项。
关于 will-change 的常见误解
很多初级开发者看到 will-change 会觉得“加上这个就一定会变顺滑”。但事实并不是这样。
will-change 有下面这些特性。
- 不是性能保证选项
- 不是强制浏览器优化的功能
- 错误使用只会增加内存使用量
- 不能解决动画性能问题的根本原因
如果动画卡顿,通常应该先检查下面几点。
- 是否正在动画化
top、left、width、height这样成本较高的属性 - 是否可以改为以
transform、opacity为中心 - 是否有太多 DOM 元素同时移动
- repaint 或 layout 是否过度发生
也就是说,will-change 更接近最后的微调工具,不是拯救结构性错误动画的解决方案。
按实务标准整理
在实际工作中,可以按下面标准判断是否使用 will-change。
可以使用的情况
- 即将发生变化的元素很明确
- 动画以
transform、opacity为中心 - 实际存在性能问题,或确实需要改善顺滑度
- 可以在变化前添加,并在结束后移除
应避免的情况
- 没有特别理由,只是习惯性添加
- 一次性应用到很多元素
- 没有性能测量,只是觉得“看起来不错”就加
- 大量使用会引发布局变化的属性,却想用
will-change解决
结论
will-change 是 CSS 中为了性能优化而存在的属性,但它的本质始终是给浏览器的提前提示。
核心很简单。
will-change 应该只在必要的时刻、必要的元素上、短时间使用。
如果想改善动画性能,首先应该围绕 transform 和 opacity 重新设计,然后只在真正需要时添加 will-change。
盲目全局添加并不是优化,更接近于浪费性能资源。
一句话总结:
will-change 是性能提示,不是万能解决方案。
如果需要,下一步可以把这篇文章再整理成更适合博客风格的版本,或改写成以示例为中心的初学者版本。

Webアニメーションやインタラクションを作っていると、「この要素がもっと滑らかに動いてほしい」と思うことがあります。そのとき一度は目にするCSSプロパティが will-change です。
このプロパティは名前だけ見ると、すごいパフォーマンス最適化オプションのように感じます。しかし実際には、かなり慎重に使うべき「ブラウザへのヒント」に近いものです。うまく使えば役立ちますが、無分別に使うと逆にパフォーマンスが悪くなることもあります。
この記事では、will-change が正確には何なのか、なぜ存在するのか、いつ使うべきなのか、そして実際にどう使うのかを順番に整理します。
will-changeとは?
will-change は、要素に何らかの変化がまもなく起こることをブラウザへ事前に知らせるCSSプロパティです。
つまり、開発者がブラウザにこう伝えているようなものです。
「この要素はこれから transform や opacity のようなプロパティが変わる予定だから、先に準備しておいて。」
ブラウザはこのヒントをもとに、レンダリング最適化を事前に行うことがあり、状況によってはアニメーションやトランジションがより滑らかに動作します。
基本例はとても単純です。
.box {
will-change: transform;
}
このコードは、.box 要素の transform 値がすぐに変わる可能性があるので、ブラウザが事前に準備できるようにするヒントです。
なぜ必要なのか?
ブラウザは画面を描画するとき、HTMLとCSSを一度に処理するわけではありません。複数の段階を通ってレンダリングします。どのプロパティが変わるかによって、layoutを再計算したり、paintをやり直したり、compositing段階だけを再実行したりします。
このとき transform や opacity のように比較的効率よく処理できるプロパティが頻繁に変わる場合、ブラウザがあらかじめ準備しておくことで、アニメーションがより自然に見える可能性があります。
つまり、will-change はパフォーマンスを直接上げる魔法のようなプロパティではなく、ブラウザがより良い最適化を行えるように事前情報を提供する役割を持ちます。
よく使う値
will-change には主に次のような値を入れます。
1. transform
要素の移動、回転、拡大・縮小などの変形が起こるときに使います。
.card {
will-change: transform;
}
2. opacity
透明度の変化が予定されているときに使います。
.modal {
will-change: opacity;
}
3. 複数の値を一緒に使う
.panel {
will-change: transform, opacity;
}
スライドしながら同時にフェード効果が入るUIでよく見られる形です。
4. auto
デフォルト値です。特別な最適化ヒントを与えない通常状態と考えればよいです。
.element {
will-change: auto;
}
実際の使用例
最も分かりやすい例は、ボタンを押したときにボックスが横へ移動する場合です。
HTML
<div class="box"></div>
<button id="moveBtn">Move</button>
CSS
.box {
width: 120px;
height: 120px;
background: royalblue;
transition: transform 0.4s ease;
}
.box.animate {
will-change: transform;
transform: translateX(200px);
}
JavaScript
const box = document.querySelector('.box');
const button = document.querySelector('#moveBtn');
button.addEventListener('click', () => {
box.classList.add('animate');
box.addEventListener(
'transitionend',
() => {
box.style.willChange = 'auto';
},
{ once: true }
);
});
この例はどう動くのか?
ボタンをクリックすると .box に animate classが追加され、transform: translateX(200px) が適用されて要素が右へ移動します。
このとき will-change: transform も一緒に適用されるため、ブラウザはその要素の transform 変化に備えられます。結果として、状況によってはより滑らかなアニメーションが可能になります。
そしてアニメーションが終わった後は、will-change を再び auto に戻します。この部分が重要です。will-change を維持し続けると、不要なリソースを占有する可能性があるためです。
より良い使い方
実務では、will-change をCSSに常時入れておくより、変化が起こる直前に適用し、終わったら削除するほうがよいです。
たとえば次のように書けます。
const box = document.querySelector('.box');
const button = document.querySelector('#moveBtn');
button.addEventListener('click', () => {
box.style.willChange = 'transform';
requestAnimationFrame(() => {
box.style.transform = 'translateX(200px)';
});
box.addEventListener(
'transitionend',
() => {
box.style.willChange = 'auto';
},
{ once: true }
);
});
この方式がより良い理由は明確です。
第一に、本当に変化が必要なときだけ will-change を適用します。
第二に、アニメーションが終わったらすぐ解除します。
第三に、ブラウザが不要な最適化状態を長く維持しないようにできます。
いつ使うとよいのか?
will-change はすべての要素に付けるプロパティではありません。次のような、パフォーマンス感度の高いインタラクションで限定的に使うのが適切です。
使いやすい場合
- 大きな要素にhoverアニメーションが入る場合
- サイドメニューがslideで開閉する場合
- card dragインタラクションがある場合
- 複雑なUIトランジションで
transform、opacityが頻繁に変わる場合
たとえばサイドパネルが開くときは次のように考えられます。
.sidebar {
transition: transform 0.3s ease;
}
.sidebar.is-opening {
will-change: transform;
}
つまり、「まもなく動く要素」が明確なときだけ使うべきです。
いつ使うべきではないのか?
この部分のほうが重要です。will-change は乱用すると、かえってパフォーマンスが悪くなることがあります。
代表的に良くない例は次のようなコードです。
* {
will-change: transform;
}
また、次のようなコードも危険です。
.card {
will-change: transform;
}
これ自体が必ず間違いというわけではありません。ただし .card が数十個、数百個存在する場合は話が変わります。ブラウザは多くの要素を事前に最適化しようとしてメモリをより多く使い、結果的に全体のパフォーマンスが落ちることがあります。
つまり、will-change は「たくさん使うほど良いオプション」ではなく、「本当に必要な要素にだけ短く使うオプション」です。
will-changeについてのよくある誤解
多くの初級開発者は will-change を見ると、「これを入れれば必ず滑らかになる」と考えがちです。しかしそれは事実ではありません。
will-change には次のような性質があります。
- パフォーマンス保証オプションではない
- ブラウザ最適化を強制する機能ではない
- 間違って使うとメモリ使用量だけ増やすことがある
- アニメーション性能問題の根本原因は解決しない
アニメーションがカクつくなら、まず確認すべきことは通常次のような点です。
top、left、width、heightのようなコストの大きいプロパティをアニメーションしていないかtransform、opacity中心に変えられないか- あまりにも多くのDOM要素が同時に動いていないか
- repaintやlayoutが過度に発生していないか
つまり、will-change は最後の微調整に近いツールであり、構造的に間違ったアニメーションを救う解決策ではありません。
実務基準で整理すると
実務で will-change を見るときは、次の基準で判断するとよいです。
使ってよい場合
- まもなく変化が起こる要素が明確
transform、opacity中心のアニメーション- 実際に性能課題がある、または滑らかさの改善が必要
- 変化直前に入れて、終わった後に削除できる
避けるべき場合
- 特別な理由なく習慣で入れる場合
- 多くの要素に一括で適用する場合
- 性能測定なしに、なんとなく「良さそうだから」入れる場合
- layout変更の大きいプロパティを多用しながら
will-changeで解決しようとする場合
結論
will-change はCSSでパフォーマンス最適化のために存在するプロパティですが、その正体はあくまでブラウザへの事前ヒントです。
要点はシンプルです。
will-change は必要な瞬間に、必要な要素にだけ、短く使うべきです。
アニメーション性能を改善したいなら、まず transform と opacity を中心に設計を変え、その後本当に必要な場合だけ will-change を追加するのが正しいです。
むやみにグローバルに入れるのは最適化ではなく、むしろパフォーマンス資源の浪費に近いです。
一行でまとめるとこうです。
will-change は性能のためのヒントであり、万能の解決策ではありません。
必要であれば次の段階として、この記事をよりブログ向けに整えた版や、例中心の初心者向け版に書き直すこともできます。

Al crear animaciones o interacciones web, a veces piensas: “Ojalá este elemento se moviera con más suavidad”. La propiedad CSS que suele aparecer en ese momento es will-change.
Por el nombre, puede parecer una gran opción de optimización de rendimiento, pero en realidad se parece más a “una pista que le das al navegador” y debe usarse con cuidado. Bien usada puede ayudar, pero si se usa sin criterio puede incluso empeorar el rendimiento.
En este artículo veremos qué es exactamente will-change, por qué existe, cuándo conviene usarla y cómo se usa en la práctica.
Qué es will-change
will-change es una propiedad CSS que avisa al navegador por adelantado de que un elemento va a cambiar pronto.
Es decir, como desarrollador le estás diciendo al navegador algo así:
“Este elemento pronto va a cambiar una propiedad como transform u opacity, así que prepárate.”
Con esta pista, el navegador puede realizar optimizaciones de renderizado por adelantado y, en algunos casos, las animaciones o transiciones pueden ejecutarse con más suavidad.
El ejemplo básico es muy simple.
.box {
will-change: transform;
}
Este código indica que el valor transform del elemento .box puede cambiar pronto, para que el navegador se prepare con antelación.
Por qué es necesaria
Cuando el navegador dibuja la pantalla, no procesa HTML y CSS de una sola vez. Renderiza a través de varias etapas. Según qué propiedad cambie, puede tener que recalcular layout, repintar o solo volver a ejecutar la etapa de composición.
Cuando cambian con frecuencia propiedades relativamente eficientes de procesar, como transform u opacity, la animación puede verse más natural si el navegador se prepara de antemano.
Así que will-change no es una propiedad mágica que aumente directamente el rendimiento. Su papel es dar información anticipada para que el navegador pueda optimizar mejor.
Valores comunes
Los valores que se suelen usar con will-change son estos.
1. transform
Se usa cuando se espera una transformación como movimiento, rotación, ampliación o reducción del elemento.
.card {
will-change: transform;
}
2. opacity
Se usa cuando se espera un cambio de opacidad.
.modal {
will-change: opacity;
}
3. Varios valores juntos
.panel {
will-change: transform, opacity;
}
Es una forma frecuente en UI donde un panel se desliza y al mismo tiempo tiene un efecto de fade.
4. auto
Es el valor predeterminado. Puedes entenderlo como el estado normal en el que no se da ninguna pista especial de optimización.
.element {
will-change: auto;
}
Ejemplo práctico
El ejemplo más fácil de entender es un cuadro que se mueve hacia un lado al pulsar un botón.
HTML
<div class="box"></div>
<button id="moveBtn">Move</button>
CSS
.box {
width: 120px;
height: 120px;
background: royalblue;
transition: transform 0.4s ease;
}
.box.animate {
will-change: transform;
transform: translateX(200px);
}
JavaScript
const box = document.querySelector('.box');
const button = document.querySelector('#moveBtn');
button.addEventListener('click', () => {
box.classList.add('animate');
box.addEventListener(
'transitionend',
() => {
box.style.willChange = 'auto';
},
{ once: true }
);
});
Cómo funciona este ejemplo
Al hacer clic en el botón, se añade la clase animate a .box, se aplica transform: translateX(200px) y el elemento se mueve hacia la derecha.
En ese momento también se aplica will-change: transform, por lo que el navegador puede prepararse para el cambio de transform de ese elemento. Según la situación, esto puede permitir una animación más suave.
Después de que termine la animación, will-change vuelve a auto. Esta parte es importante. Si will-change se mantiene activo, puede ocupar recursos innecesarios.
Una mejor forma de usarlo
En proyectos reales, suele ser mejor aplicar will-change justo antes de que ocurra el cambio y quitarlo cuando termina, en lugar de dejarlo permanentemente en el CSS.
Por ejemplo:
const box = document.querySelector('.box');
const button = document.querySelector('#moveBtn');
button.addEventListener('click', () => {
box.style.willChange = 'transform';
requestAnimationFrame(() => {
box.style.transform = 'translateX(200px)';
});
box.addEventListener(
'transitionend',
() => {
box.style.willChange = 'auto';
},
{ once: true }
);
});
La razón por la que este patrón es mejor es clara.
Primero, will-change se aplica solo cuando el cambio realmente es necesario.
Segundo, se elimina inmediatamente cuando termina la animación.
Tercero, evita que el navegador mantenga durante demasiado tiempo un estado de optimización innecesario.
Cuándo conviene usarlo
will-change no es una propiedad para añadir a todos los elementos. Debe usarse de forma limitada en interacciones sensibles al rendimiento, como estas.
Casos adecuados
- Un elemento grande tiene una animación hover
- Un menú lateral se abre y cierra con una animación de slide
- Hay interacción de arrastre de tarjetas
- En una transición de UI compleja cambian con frecuencia
transformyopacity
Por ejemplo, al abrir un panel lateral, puedes pensarlo así.
.sidebar {
transition: transform 0.3s ease;
}
.sidebar.is-opening {
will-change: transform;
}
Es decir, debe usarse solo cuando está claro que “este elemento se moverá pronto”.
Cuándo no conviene usarlo
Esta parte es más importante. Si will-change se abusa, el rendimiento puede empeorar.
Un mal ejemplo típico es este:
* {
will-change: transform;
}
Este tipo de código también es peligroso:
.card {
will-change: transform;
}
Esto no está necesariamente mal por sí solo. Pero si existen decenas o cientos de elementos .card, la historia cambia. El navegador intentará optimizar muchos elementos por adelantado, usará más memoria y el rendimiento general puede caer.
Por tanto, will-change no es una opción que mejore cuanto más se use. Es una opción para usar brevemente y solo en elementos que realmente lo necesitan.
Malentendidos comunes sobre will-change
Muchos desarrolladores principiantes ven will-change y piensan: “si añado esto, todo será más suave”. Pero eso no es cierto.
will-change tiene estas características.
- No garantiza rendimiento
- No fuerza la optimización del navegador
- Mal usada puede aumentar solo el uso de memoria
- No resuelve la causa raíz de los problemas de rendimiento en animaciones
Si una animación se entrecorta, lo primero que conviene revisar suele ser:
- Si estás animando propiedades costosas como
top,left,widthoheight - Si puedes cambiar a
transformyopacity - Si demasiados elementos DOM se están moviendo al mismo tiempo
- Si hay demasiado repaint o layout
En otras palabras, will-change está más cerca de una herramienta de ajuste fino final. No es una solución que rescate animaciones estructuralmente mal planteadas.
Resumen con criterio de trabajo real
En trabajo real, puedes evaluar will-change con estos criterios.
Casos en los que se puede usar
- Está claro qué elemento va a cambiar pronto
- La animación se centra en
transformuopacity - Existe un problema real de rendimiento o necesidad de mejorar suavidad
- Puede añadirse justo antes del cambio y eliminarse al terminar
Casos que conviene evitar
- Añadirlo por costumbre sin una razón concreta
- Aplicarlo a muchos elementos a la vez
- Añadirlo sin medir rendimiento, solo porque “parece bueno”
- Intentar solucionar con
will-changeanimaciones que abusan de propiedades con gran coste de layout
Conclusión
will-change existe en CSS para optimización de rendimiento, pero su verdadera naturaleza es una pista anticipada para el navegador.
La clave es simple.
Usa will-change solo en el momento necesario, solo en el elemento necesario y por poco tiempo.
Si quieres mejorar el rendimiento de animaciones, primero diseña alrededor de transform y opacity, y luego añade will-change solo cuando realmente haga falta.
Añadirlo globalmente sin pensar no es optimización. Se parece más a desperdiciar recursos de rendimiento.
En una línea:
will-change es una pista de rendimiento, no una solución universal.
Si hace falta, este artículo puede refinarse después en una versión más adecuada para blog o reescribirse como una versión para principiantes centrada en ejemplos.