Explain Codes LogoExplain Codes Logo

How to dynamically create CSS class in JavaScript and apply?

javascript
dynamic-styles
css-in-js
responsive-design
Nikita BarsukovbyNikita Barsukov·Sep 17, 2024
TLDR

A quick-fire way to create and apply a CSS class in JavaScript:

  1. Assuming omnipresence of a stylesheet:

    const styleSheet = document.styleSheets[0];
  2. Summoning a new rule:

    styleSheet.insertRule(`.dynamic-class { color: red; }`, styleSheet.cssRules.length);
  3. Blessing an element with the new class:

    document.getElementById('elementId').classList.add('dynamic-class');

What's happening under the hood? We're sneakily injecting .dynamic-class with a red text into the first stylesheet and painting an element with the id elementId in alluring red!

No stylesheet, no problem

What if stylesheets are more elusive than big foot? Create one!

// Couldn't locate a stylesheet? Fascinating! Let's build one, shall we? if(document.styleSheets.length === 0) { var style = document.createElement('style'); document.head.appendChild(style); }

Behold, your squeaky-new stylesheet, ready to embrace your CSS rules!

Bespoke CSS classes on-demand

function createCSSSelector(selector, style) { // stylesheet undetected? Head element missing? Hmm...this isn't the CSS planet! if (!document.styleSheets || document.getElementsByTagName('head').length === 0) return; const styleSheet = document.styleSheets[0] || ((style) => { // Hi there, how about a virgin stylesheet for your style cravings! const newStyle = document.createElement('style'); newStyle.appendChild(document.createTextNode("")); document.head.appendChild(newStyle); return newStyle.sheet; })(); // Don't blink! Your style rule will be ready in 1...2...3... styleSheet.insertRule(selector + "{" + style + "}", styleSheet.cssRules.length); } createCSSSelector('.dynamic-class', 'color: green;');

Here, we have a handy function to stamp out the selectors with the required style. It also ensures there's a stylesheet sensibly waiting to perform its duty.

Adapting to dynamic changes

// Let's make some CSS magic happen as the browser goes on a resizing spree. window.addEventListener('resize', function() { const width = window.innerWidth; const dynamicWidthClass = `width-${width}`; createCSSSelector(`.${dynamicWidthClass}`, `width: ${width}px;`); document.body.classList.add(dynamicWidthClass); });

In this neat little trick, we link element width with the window's width. This makes the design amazingly responsive without our predefined CSS bearing the load.

A look at CSS-in-JS libraries

For applications striving for something a little more complex or nuanced, CSS-in-JS libraries like Emotion or Styled Components offer a sophisticated bouquet of options.

// Styling in Styled Components while coding in React import styled from 'styled-components'; const DynamicDiv = styled.div` background-color: ${props => props.bgColor}; `; // A dynamic component wearing a dynamic style <DynamicDiv bgColor="papayawhip">It's astonishing how dynamic we can get!</DynamicDiv>

Libraries like these bring styles and logic closer than ever before, making for a potent blend of power for dynamic styles.

Keeping styles interactive

// Hover over...and here's a surprise! document.querySelector('.button').addEventListener('mouseover', function(e) { createCSSSelector('.button:hover', 'background-color: yellow;'); });

With dynamic creation of CSS classes, your designs can spring a surprise with changes in response to user actions like hover, or click, on-the-go.

Accounting for compatibility quirks

function createAndApplyClass(className, style) { if (document.createStyleSheet) { // Looks like we're swimming with old-Ed Internet Explorer! document.createStyleSheet().addRule(`.${className}`, style); } else { const styleSheet = document.styleSheets[0] || document.styleSheets; styleSheet.insertRule(`.${className} { ${style} }`, styleSheet.cssRules.length); } }

This function is your insurance for working in the retro neighborhood of Internet Explorer 7 and 8 and serves a compatible CSS class making experience.

Dynamic themes and more

The ability to bake CSS classes dynamically using JavaScript gives you the power to colour your projects with the hues of dynamic themes, interactive styles, and responsive designs that truly calibrate to the beat of user interactions.