Scripting CSS with JavaScript: classList, Inline Styles, Computed Styles, Custom Properties and Animations
Control presentation from JavaScript: toggling classes, the style property and units, cssText and setProperty, CSS custom properties, getComputedStyle, switching and constructing stylesheets, matchMedia, transition and animation events, the Web Animations API and prefers-reduced-motion.
kvi5hnuCode Sprout team member6 min readOn this page
HTML describes a page's content and CSS describes how it looks. JavaScript can change the look in several ways, from toggling a class to editing stylesheets, and it can read the browser's final calculated styles. Choosing the right technique keeps styling in CSS where designers can maintain it, and avoids layout performance problems.

Classes first
The most maintainable approach is to define states in CSS and have JavaScript only switch classes:
.panel { max-height: 0; overflow: hidden; transition: max-height 0.3s ease; }
.panel.open { max-height: 40rem; }
.hidden { display: none; }
toggleButton.addEventListener("click", () => {
const isOpen = panel.classList.toggle("open");
toggleButton.setAttribute("aria-expanded", String(isOpen)); // keep accessibility in sync
});
The visual design stays in the stylesheet, multiple properties change together, and media queries and themes keep working. The hidden HTML attribute (element.hidden = true) is a built-in alternative for simply hiding something.
Inline styles: element.style
element.style is a CSSStyleDeclaration representing the element's inline style attribute. CSS property names become camelCase properties, and values are strings that must include units:
box.style.marginLeft = "300px"; // margin-left
box.style.backgroundColor = "#fde68a"; // background-color
box.style.transform = `translate(${x}px, ${y}px) rotate(${angle}deg)`;
box.style.marginLeft = "300"; // ignored: no unit, so it isn't valid CSS
box.style.marginLeft = ""; // remove the inline value
Invalid values are silently ignored, which is the most common reason "my style didn't apply". Other ways to work with inline styles:
box.style.cssText = "width: 10rem; height: 4rem"; // replace the whole inline style
copy.style.cssText = box.style.cssText; // copy one element's inline style
box.style.setProperty("color", "red", "important"); // dashed names, optional priority
box.style.getPropertyValue("color"); // "red"
box.style.removeProperty("color");
Reading element.style tells you only about inline styles, exactly as written. A color set in a stylesheet reads as "". For the real, final values, use computed styles.
Use inline styles for values that change continuously, such as positions during a drag or an animation driven by requestAnimationFrame. For everything else, prefer classes.
CSS custom properties
Custom properties (CSS variables) are the bridge between JavaScript values and CSS rules. Set the number in JavaScript; let CSS decide how to use it:
.progress { --percent: 0; }
.progress-bar { width: calc(var(--percent) * 1%); background: hsl(calc(var(--percent) * 1.2) 70% 45%); }
progress.style.setProperty("--percent", 72);
getComputedStyle(progress).getPropertyValue("--percent"); // "72"
// themes: change one variable on the root, and every rule using it updates
document.documentElement.style.setProperty("--accent", "#7c3aed");
Custom properties must be set with setProperty and read with getPropertyValue; the camelCase shorthand doesn't apply to them. They inherit down the tree, so setting one on a container affects every descendant that uses it.
Computed styles
getComputedStyle(element, pseudoElement?) returns the values the browser actually uses after combining stylesheets, inline styles and inheritance:
const styles = getComputedStyle(title);
styles.fontSize; // "32px": always resolved to pixels
styles.color; // "rgb(15, 23, 42)": colors in rgb() form
styles.display; // "block"
getComputedStyle(title, "::before").content; // styles of a pseudo-element
Things to know:
- The object is read-only and live: it reflects later changes.
- Lengths are resolved to absolute values (
px), so you still needparseFloatto do math with them. - Read individual longhand properties (
marginTop,borderLeftWidth). Shorthands such asmarginmay come back empty or combined. - Values like
fontFamilytell you what was requested ("Inter, system-ui, sans-serif"), not which font was actually used. Non-positioned elements often reporttop: auto. - Reading computed styles can force the browser to recalculate styles and layout, so avoid doing it inside tight loops.
For an element's actual size and position, use getBoundingClientRect() (article 112) rather than computed width and top.
Scripting stylesheets
<style> and <link rel="stylesheet"> elements are ordinary DOM elements, so you can add, remove or disable whole stylesheets:
function setTheme(name) {
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = `/themes/${name}.css`;
link.id = "theme";
const current = document.querySelector("#theme");
if (current) current.replaceWith(link);
else document.head.append(link);
}
document.querySelector("#print-preview-styles").disabled = true; // switch a sheet off
For finer control, the CSS Object Model (CSSOM) exposes each stylesheet's rules: document.styleSheets[0].cssRules, insertRule() and deleteRule(). Modern code can also create stylesheets directly in JavaScript, called constructable stylesheets, and share them between the document and shadow roots (article 113):
const sheet = new CSSStyleSheet();
sheet.replaceSync(".badge { color: white; background: crimson; border-radius: 1em; }");
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
Reacting to media queries
matchMedia evaluates a media query from JavaScript and tells you when its result changes. It's useful for behavior that CSS alone can't express:
const dark = matchMedia("(prefers-color-scheme: dark)");
applyChartColors(dark.matches);
dark.addEventListener("change", (event) => applyChartColors(event.matches));
const narrow = matchMedia("(max-width: 40rem)");
if (narrow.matches) collapseSidebar();
Transitions, animations and their events
CSS transitions animate a property whenever its value changes, so JavaScript only needs to change a class:
.toast { opacity: 1; transition: opacity 0.4s ease-in; }
.toast.fading { opacity: 0; }
toast.classList.add("fading");
toast.addEventListener("transitionend", () => toast.remove(), { once: true });
The browser fires transitionrun (when the transition is created, before any delay), transitionstart (when it visibly begins), transitionend and transitioncancel. Each event's propertyName says which property finished, and elapsedTime gives the duration in seconds. If several properties transition, transitionend fires once per property.
CSS animations (@keyframes rules plus animation-* properties) fire animationstart, animationiteration (at each repeat) and animationend, whose animationName identifies the keyframes. Triggering one is again just a class change.
The Web Animations API
element.animate(keyframes, options) runs keyframe animations from JavaScript, with the performance of CSS animations, and returns an Animation object you can control:
const animation = card.animate(
[
{ transform: "translateY(12px)", opacity: 0 },
{ transform: "translateY(0)", opacity: 1 },
],
{ duration: 300, easing: "ease-out", fill: "both" },
);
animation.pause();
animation.playbackRate = 2;
animation.play();
await animation.finished; // a promise that fulfills when the animation ends
card.classList.add("ready");
animation.finished lets animations fit naturally into async code (article 98). document.getAnimations() lists every running CSS and script animation, which helps when testing or when you need to wait for them all to settle.
Respect reduced motion
Some users get dizzy or nauseous from motion and ask their operating system to reduce it. Check the preference before animating large movements:
const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
panel.animate(keyframes, { duration: reduceMotion ? 0 : 400 });
In CSS, wrap motion in @media (prefers-reduced-motion: no-preference) { ... }.
Performance: avoid layout thrashing
Changing styles marks the layout as stale. Reading a geometry value (offsetHeight, getBoundingClientRect(), getComputedStyle(...).width) right afterwards forces the browser to recalculate the layout immediately. Alternating writes and reads in a loop forces a full layout on every iteration, which is called layout thrashing:
// slow: read, write, read, write...
for (const box of boxes) box.style.width = `${box.offsetWidth + 10}px`;
// fast: read everything first, then write everything
const widths = boxes.map((box) => box.offsetWidth);
boxes.forEach((box, i) => { box.style.width = `${widths[i] + 10}px`; });
Animate transform and opacity where possible. The browser can animate them without recalculating layout, often on the GPU, while animating width, top or margin triggers layout on every frame.
Common questions
Why doesn't element.style.color show the color from my stylesheet?
element.style reflects only inline styles. Use getComputedStyle(element).color to see the value that actually applies.
Why didn't box.style.width = 200 work?
CSS lengths need units, and invalid values are silently ignored. Use "200px" (or a template string like `${n}px`).
Should I set styles in JavaScript or toggle classes?
Toggle classes for states (open, active, error, dark), so the styling stays in CSS. Use inline styles or custom properties only for values computed at run time, like positions, progress or user-chosen colors.
How do I wait for a CSS transition to finish?
Listen for transitionend on the element (with { once: true }), or use the Web Animations API, where animation.finished is a promise.
Summary
- Prefer toggling classes; keep visual rules in CSS.
element.stylereads and writes inline styles: camelCase names, string values with units,cssTextandsetPropertyfor bulk or dashed names.- Custom properties (
--name) carry JavaScript values into CSS; set them withsetProperty. getComputedStylegives read-only, resolved final values; usegetBoundingClientRectfor geometry.- Stylesheets can be swapped, disabled, edited through the CSSOM, or created with
new CSSStyleSheet();matchMediareacts to media queries. - Transitions and animations fire start, end and iteration events;
element.animate()returns a controllableAnimationwith afinishedpromise. Honorprefers-reduced-motionand avoid layout thrashing.
Practice Questions
Why does this do nothing, and what's the fix?
box.style.left = x + 20;
Answer
A bare number isn't a valid CSS length, so the assignment is ignored. Add a unit:
box.style.left = `${x + 20}px`;
The element also needs position set to something other than static for left to have any effect.
How do you let a slider control a CSS-only progress bar?
Answer
Set a custom property from JavaScript and use it in CSS:
slider.addEventListener("input", () => {
bar.style.setProperty("--percent", slider.value);
});
.bar { width: calc(var(--percent) * 1%); }
What does getComputedStyle(p).fontSize return when the CSS says font-size: 1.5rem and the root font size is 16px?
Answer
"24px". Computed lengths are resolved to absolute pixel strings.
Why is this loop slow, and how do you fix it?
for (const el of items) el.style.height = el.scrollHeight + "px";
Answer
Each iteration reads a layout value (scrollHeight) right after the previous iteration wrote a style, which forces a fresh layout every time (layout thrashing). Read everything first, then write:
const heights = items.map((el) => el.scrollHeight);
items.forEach((el, i) => { el.style.height = `${heights[i]}px`; });
Previous: Changing the DOM: Attributes, dataset, textContent, innerHTML and Creating Elements

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.