JavaScript and CSS are core technologies for building interactive web applications. While CSS is used for styling and layout, JavaScript handles the dynamic behavior and interactivity. However, the two languages can work together to create robust UIs with dynamic styling.

In this comprehensive guide, we‘ll explore various methods for setting CSS properties in JavaScript.

Why Set CSS in JavaScript?

Here are some common reasons for setting CSS properties with JavaScript:

  • Dynamically update styles on user interaction – For example, highlight menu items on hover, show/hide elements when a button is clicked, change font colors based on data values, etc.

  • Animate CSS values – Smoothly transition CSS property values like width, opacity, transforms etc. This is the basis for most JS animation libraries.

  • Adapt UIs across viewports – Modify styling based on screen size for responsive web design. Useful for things like toggling between stacked vs spread-out grids.

  • Theme/skin switching – Change overall UI colors, fonts etc when users select themes. Helps provide consistency across an app.

  • Improved accessibility – Modify contrast, font sizes etc based on user preferences or disabilities.

  • React to data changes – As new data loads from an API, highlight certain data points using custom colors or typography.

In essence, setting CSS in JS allows web UIs to adapt and feel more dynamic or "app-like". It complements declarative CSS with imperative, conditional styling logic in JS.

Common Use Cases

Some specific examples where setting CSS in JavaScript provides value:

Dynamic Charts & Graphs

As chart data changes, modify widths, colors and positions of elements to match.

Interactive Maps

On mouse hover or tap, subtly highlight regions and cities using shadows, color overlays etc.

Shopping Cart

When items are added/removed, show animated transitions and updated totals/badges.

Form Validation

Provide real-time feedback on invalid inputs by changing borders, text prompts etc.

Activity Feeds

For notifications, animate new items sliding in and old ones fading out.

Progress Trackers

As user completes steps, check off icons, change connected elements to indicate progress.

More Immersive Gaming

For greater responsiveness, detect input to stylistically react elements on screen.

These examples leverage JavaScript to create livelier, data-coupled interfaces.

Ways to Set CSS Properties in JavaScript

There are a few main approaches for setting CSS from JS:

1. Inline Styles

This involves setting the JavaScript style property on DOM elements:

const el = document.getElementById("myElement");

el.style.color = "red";  
el.style.fontSize = "2em"; 

Pros:

  • Simple syntax – easy to use
  • Specificity of 1000 – overrides other rules

Cons:

  • Styles only apply to individual element, can‘t reuse
  • Media queries not supported
  • Lots of imperative DOM/style code

2. CSS Classes

Here we conditionally add/remove/toggle CSS classes:

el.classList.add("highlighted");
el.classList.toggle("visible");  

CSS:

.highlighted {
  color: yellow; 
}

.visible {
  display: block; 
}

Pros:

  • Reusable class-based styling
  • Supports media queries
  • Separates concerns

Cons:

  • Still imperative

3. StyleSheet API

Directly modify CSS stylesheets:

sheet.insertRule("header { color: green; }");

sheet.rules[0].style.color = "blue"; 

Pros:

  • Maximum flexibility
  • Add keyframes etc

Cons:

  • Cumbersome API
  • Browser inconsistencies

Bonus: CSS-in-JS Libraries

Libraries like Styled Components allow writing CSS code inline:

const Heading = styled.h1`
  font-size: 2rem;  
  color: ${props => props.color};   
`;

render(
  <Heading color="red">Hello!</Heading>
) 

Let‘s analyze the performance and usability of these options…

Performance Considerations

Dynamically modifying styles via JavaScript can have performance implications in some cases.

Common Bottlenecks

  • Excessive DOM reads/writes
  • Frequent style recalculations
  • Layout thrashing

Some optimization strategies:

  • Batch DOM reads/writes using document.createDocumentFragment()
  • Debounce rapid style changes with requestAnimationFrame() or setTimeout()
  • Limit reflows by changing className rather than multiple inline styles
  • Cache style references in variables vs DOM lookups
  • Use css custom properties for quick theme variable changes

By minimizing style recalcs and reflows, UIs can remain buttery smooth.

Leveraging Modern CSS Features

Newer CSS specs provide tools to make dynamic styling easier:

CSS Custom Properties

Store styles as vars and update imperatively:

:root {
  --color: blue;
  --spacing: 20px; 
}

span { 
  color: var(--color);
  margin: var(--spacing);
}
document.documentElement.style.setProperty("--color", "red");

CSS Variables in Media Queries

Vary styles across breakpoints:

@media (max-width: 700px) {
  :root {
    --color: hotpink;
    --font-size: 4vw;
  }
}

Shadow Parts

Style shadow DOM parts from main document:

customEl.part.textContent = "Styled!"; 

customEl::part(text) {
  color: blue;
}

These new capabilities expand possibilities for dynamic styling in JavaScript.

CSS Animation Options

Here are some popular options for animating style changes:

CSS Transitions

Easy built-in method with good performance:

.slide {
  transform: translateX(0);
  transition: transform 0.5s ease;  
}
el.classList.add(‘slide‘);
el.style.transform = "translateX(100px)";

Greensock (GSAP)

Robust timeline-based animations:

gsap.to("#box", {duration: 1, x: 100, opacity: 0});  

gsap.from(".text", {duration: 1, delay: 1, y: -50, opacity: 0}) 

Pros: Timelines, easings, sequencing. Smooth performance via requestAnimationFrame()

Cons: Steeper learning curve than CSS transitions.

Anime.js

Lightweight JavaScript animation engine:

anime({
  targets: ‘#box‘,
  translateX: 250,
  rotate: ‘1turn‘,
  backgroundColor: ‘#FFF‘,
  duration: 800
});

Pros: Simple API, small file size
Cons: Less flexibility than Greensock

React Spring

Animation library designed for React:

import { useSpring, animated } from ‘react-spring‘;

function Component() {
  const fade = useSpring({opacity: 1, from: {opacity: 0}});

  return <animated.div style={fade}>I will fade in!</animated> 
}

Built to integrate nicely with React state and lifecycle events.

There are many other options like Velocity.js, Snap.svg etc catering to different animation use cases.

Browser Support

The StyleSheet API methods have relatively broad browser support, but with some caveats:

Method IE 11 Chrome Firefox Safari
insertRule
deleteRule
addRule

(Limited support)

  • IE11 lacks support for some key methods like insertRule
  • Safari has issues dynamically modifying @keyframes
  • Browser prefixes needed in some cases

Usage Statistics

CSS-in-JS libraries have seen massive growth recently:

  • Over 65,000 npm downloads per week of styled-components and emotion.
  • Adopted by major companies like Uber, Dropbox, Airbnb.
  • Allow easier server-side rendering critical CSS.

These declarative styling tools integrate nicely with modern frameworks.

Key Takeaways

  • Use JavaScript to create reactive, dynamic UIs
  • Balance simplicity and flexibility when modifying CSS
  • Optimize performance by batching changes
  • Take advantage of new features like custom properties
  • Animate carefully to avoid jank
  • Many tools integrate JS and CSS coding nicely

Conclusion

JavaScript provides immense control over styling behavior to augment declarative CSS. Mastering techniques like inline styles, class manipulation and StyleSheet API access unlocks new possibilities.

With performance optimizations and leveraging emerging standards, JavaScript will continue expanding the frontiers of dynamic UI development.

Similar Posts