How to dynamically create CSS class in JavaScript and apply?
A quick-fire way to create and apply a CSS class in JavaScript:
-
Assuming omnipresence of a stylesheet:
-
Summoning a new rule:
-
Blessing an element with the new 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!
Behold, your squeaky-new stylesheet, ready to embrace your CSS rules!
Bespoke CSS classes on-demand
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
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.
Libraries like these bring styles and logic closer than ever before, making for a potent blend of power for dynamic styles.
Keeping styles interactive
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
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.
Was this article helpful?