Explain Codes LogoExplain Codes Logo

How do you add CSS with JavaScript?

javascript
prompt-engineering
cross-browser-compatibility
performance
Alex KataevbyAlex Kataev·Feb 13, 2025
TLDR

Quickly style an element by targeting it with querySelector and assigning styles via .style:

document.querySelector('.myElement').style.cssText = 'color: blue; font-size: 20px;';

````.cssText``` allows you to apply multiple styles. For setting a single property:

document.querySelector('.myElement').style.backgroundColor = 'lightgreen';

But what if you want to add CSS rules dynamically, based on certain events or conditions? You can create and append a <style> element to the head of your document:

const style = document.createElement('style'); style.type = 'text/css'; let styles = `body { background: #f3f3f3; } .myClass { color: red; }`; // Dressing up the body like it's going to prom! style.appendChild(document.createTextNode(styles)); document.head.appendChild(style);

Crafting dynamic styles

Multi-line CSS with template literals

In the case of multi-line CSS, ES6 template literals (denoted by backticks `) dramatically improve readability:

const styleEl = document.createElement('style'); styleEl.type = 'text/css'; styleEl.innerHTML = ` body { margin: 0; } .dynamic-class { color: green; } #dynamic-id { font-size: 20px; } `; // Bye indentation errors and hello neat CSS! document.head.appendChild(styleEl);

Adding styles with DOM manipulation

You can leverage DOM Level 2 CSS with its method insertRule to insert new rules into an existing stylesheet:

const sheet = document.styleSheets[0]; // Adding a rule like it's nobody's business sheet.insertRule('.newClass { color: blue; }', sheet.cssRules.length);

For browsers like Internet Explorer 8 and below that don’t support insertRule, you must settle for addRule.

const sheet = document.styleSheets[0]; if(sheet.addRule) { // When life gives you IE8, use addRule! sheet.addRule('.newClass', 'color: blue;', -1); }

One-liner magic

Here’s a handy one-liner to add CSS:

const addCSS = css => document.head.appendChild(document.createElement("style")).innerHTML = css;

You can call this function as:

addCSS('body { background: coral; } .highlight { font-weight: bold; }');

Keeping best practices in mind

Cross-browser compatibility

With dynamic CSS, keep in mind that cross-browser compatibility is essential. Ensure your insertRule or addRule methods provide fallbacks for older browsers.

Security implications

When injecting styles with JavaScript, be wary of CSS Injection attacks. Treat user-supplied data with caution and sanitize it before adding styles.

Performance pointers

For frequent style changes, consider the performance. Minimize direct DOM manipulation to avoid high reflow and repaint costs.