Il browser trasforma i cambiamenti CSS in pixel attraverso una pipeline, e diversi cambiamenti attivano diverse fasi (più o meno costose):
Style → Layout (reflow) → Paint → Composite
Il browser trasforma i cambiamenti CSS in pixel attraverso una pipeline, e diversi cambiamenti attivano diverse fasi (più o meno costose):
Style → Layout (reflow) → Paint → Composite
/* ❌ trigger LAYOUT (reflow) — costly, recalculates geometry every frame */
width, height, top, left, margin, padding, font-size
/* ⚠️ trigger PAINT — repaint pixels */
color, background, box-shadow, border-radius
/* ✅ trigger only COMPOSITE — GPU, no layout/paint */
transform, opacity
Questa è la regola di performance più importante: anima transform e opacity, non width/top/margin. Animare proprietà di layout riesegue il layout ogni frame (jank); i transform sono compositi dalla GPU (fluido 60fps).
/* ❌ janky */ @keyframes a { to { left: 300px; width: 200px; } }
/* ✅ smooth */ @keyframes b { to { transform: translateX(300px) scaleX(2); } }
.animated { will-change: transform; } /* promotes to its own GPU layer ahead of time */
Usa will-change solo su elementi che stai per animare — usarlo eccessivamente spreca memoria creando troppi layer.
// ❌ read-write-read-write forces multiple synchronous reflows
for (const el of els) { el.style.width = el.offsetWidth + 10 + "px"; }
// ✅ batch reads, then writes
const widths = els.map(el => el.offsetWidth);
els.forEach((el, i) => el.style.width = widths[i] + 10 + "px");
- contain: layout/paint — isolate a subtree so changes don't reflow the whole page
- content-visibility: auto — skip rendering offscreen content
- minimize deep selectors and huge unused stylesheets
La performance del rendering è principalmente questione di non attivare il layout ripetutamente.
Sapere che transform/opacity sono solo composite (economici) mentre width/top/margin forzano il reflow (costosi) — più evitare il layout thrashing e usare contain/content-visibility — è ciò che mantiene le animazioni a 60fps e le pagine veloci.