Performance: Dynamic inline styles
Dynamic inline styles affect rendering speed and layout stability by causing style recalculations and potential layout shifts when styles change frequently.
<div class:colored={color === 'red'} style="font-size: {fontSize}px;"></div> <style> .colored { color: red; } </style>
<div style="color: {color}; font-size: {fontSize}px; margin-left: {margin}px;"></div>| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Frequent dynamic inline styles on size/position | Low (single element) | Multiple reflows per update | High paint cost due to layout changes | [X] Bad |
| Mostly CSS classes with minimal inline styles | Low | Single reflow or none | Lower paint cost | [OK] Good |
{color}.style="background-color: {color};". Other options use incorrect variable interpolation.<div style="width: {width + 'px'};"></div> correctly uses {width + 'px'}. <div style="width: width + 'px';"></div> lacks braces, B and C incorrectly place 'px' outside the braces. <script>
let size = 100;
</script>
<div style="width: {size}px; height: {size}px; background-color: 'red'">Box</div><script>
let color = 'blue';
</script>
<div style="color: {color}">Text</div>status variable with values 'success', 'warning', or 'error'. Which is the best way to apply dynamic inline styles for this?<div style="color: {status === 'success' ? 'green' : status === 'warning' ? 'orange' : 'red'}">Status</div> uses a nested ternary operator inside curly braces to select the correct color string based on status.<div style="color: {status == 'success' && 'green' || status == 'warning' && 'orange' || 'red'}">Status</div> uses logical operators which can cause unexpected results. <div class={status} >Status</div> <style>.success { color: green; } .warning { color: orange; } .error { color: red; }</style> uses classes and CSS, not inline styles. <div style="color: {status}">Status</div> sets color to the literal status string, which is invalid color.Pass the test and this pattern moves unknown