JavaScript can read and write an element's CSS directly through the DOM, letting you build dynamic layouts, animations, and full theming systems. This lesson covers the .style property and its kebab-case-to-camelCase mapping, window.getComputedStyle() for reading rendered values, and updating CSS custom properties (variables) with setProperty() for instant, app-wide theme changes.
1JavaScript Style Modification & CSS Variables | UI Tutorial - In-Depth Guide Part 1
Styles make your app feel alive. In JavaScript, you can override any CSS property to create dynamic layouts and effects.
// Visual Transformation2JavaScript Style Modification & CSS Variables | UI Tutorial - In-Depth Guide Part 2
The .style property allows you to set inline styles. Important: CSS properties with dashes become camelCase in JS.
const box = document.querySelector('.box');
box.style.backgroundColor = 'red';
box.style.marginTop = '20px';3JavaScript Style Modification & CSS Variables | UI Tutorial - In-Depth Guide Part 3
Setting styles is easy, but READING them from the .style object only works for inline styles. To get the ' 'real' rendered style, use window.getComputedStyle.
const box = document.querySelector('.box');
const styles = window.getComputedStyle(box);
console.log(styles.width); // Gets final rendered width4JavaScript Style Modification & CSS Variables | UI Tutorial - In-Depth Guide Part 4
CSS Variables (Custom Properties) are the most powerful way to theme. You update them using setProperty on the style object.
document.documentElement.style.setProperty('--main-color', '#ff0099');5JavaScript Style Modification & CSS Variables | UI Tutorial - In-Depth Guide Part 5
By updating a single CSS variable, you can change the theme of your entire application instantly with one line of JS.
<h1>Theme: Updated</h1>6JavaScript Style Modification & CSS Variables | UI Tutorial - In-Depth Guide Part 6
Combination: You can calculate new values based on computed styles and apply them to create complex animations.
const current = parseFloat(styles.height);
box.style.height = (current + 10) + 'px';7JavaScript Style Modification & CSS Variables | UI Tutorial - In-Depth Guide Part 7
Design meets Logic: You are now crafting the visual experience of your application dynamically.
<h1>Style: Dynamic</h1>8JavaScript Style Modification & CSS Variables | UI Tutorial - In-Depth Guide Part 8
Styling mastered! You can now paint with code.
<h1>Visuals: Reactive</h1>9JavaScript Style Modification & CSS Variables | UI Tutorial - In-Depth Guide Part 9
Next, we' 'Event Listeners' to make your app truly interactive.
<h1>Next: Events</h1>10Step-by-Step Breakdown
Styles make your app feel alive. In JavaScript, you can override any CSS property to create dynamic layouts and effects.
The .style property allows you to set inline styles. Important: CSS properties with dashes become camelCase in JS.
Setting styles is easy, but READING them from the .style object only works for inline styles. To get the ' 'real' rendered style, use window.getComputedStyle.
Checkpoint: How would you write the CSS property ' 'font-size' in JavaScript using camelCase?
- āfont-size
- āfontSize
- āfont_size
CSS Variables (Custom Properties) are the most powerful way to theme. You update them using setProperty on the style object.
By updating a single CSS variable, you can change the theme of your entire application instantly with one line of JS.
Checkpoint: Does the .style property allow you to read styles defined in an external .css file?
- āYes, it sees all styles
- āNo, only styles set directly on the element
Combination: You can calculate new values based on computed styles and apply them to create complex animations.
Design meets Logic: You are now crafting the visual experience of your application dynamically.
Checkpoint: Which global function provides a read-only object containing all the final CSS properties of an element?
- āgetStyles()
- āwindow.getComputedStyle()
Styling mastered! You can now paint with code.
Next, we' 'Event Listeners' to make your app truly interactive.
Level Up š
Advanced cheat sheets, SEO tricks, and interview prep for this topic.
Browser Support
Fully supported.
Fully supported.
Fully supported.
Fully supported.
Accessibility (A11y)
1Respect prefers-reduced-motion Before Triggering JS-Driven Animations
Style changes driven by JavaScript (sliding panels, animated counters, parallax effects) should check `window.matchMedia('(prefers-reduced-motion: reduce)')` and skip or shorten the animation for users who've indicated they're sensitive to motion, rather than forcing every visitor through the same visual effect.
SEO Implications
- 1
Layout Thrashing from Reading and Writing Styles in a Loop Can Hurt Interaction Metrics
Repeatedly calling getComputedStyle (a read) and then setting .style (a write) inside a loop forces the browser to recalculate layout on every iteration, which can visibly stall the page and hurt Interaction to Next Paint ā a Core Web Vitals metric that factors into search ranking.
Best Practices
Batch Style Reads and Writes Separately to Avoid Layout Thrashing
Read every getComputedStyle value you need first, then perform all your .style writes afterward, rather than interleaving reads and writes ā mixing them forces the browser to repeatedly recalculate layout mid-loop, which is measurably slower.
Prefer Toggling a CSS Class Over Setting Many Individual Inline Styles
Setting `el.classList.add('active')` and letting a stylesheet define what 'active' looks like keeps styling centralized and cacheable by the browser, versus setting five or six individual .style properties in JavaScript every time state changes.
Frequent Bugs
Setting el.style.margin-top = '10px' throws a syntax error or silently does nothing.
The .style object requires camelCase property names in JavaScript, not the dashed CSS syntax ā margin-top must be written as el.style.marginTop, since a hyphen isn't valid inside a JavaScript property accessor written with dot notation.
Reading el.style.width returns an empty string even though the element clearly has a visible width applied via a CSS class.
el.style only reflects inline styles explicitly set via the style attribute or JavaScript's .style API ā it does not report styles coming from an external stylesheet or class. Use window.getComputedStyle(el).width instead to read the actual, fully-resolved rendered width.
Real-World Examples
Building a Dark Mode Toggle with CSS Variables
A site needed a single toggle button that switched the entire color scheme instantly, without touching dozens of individual elements or maintaining two full duplicate stylesheets.
// CSS: :root { --bg: #fff; --text: #111; } [data-theme='dark'] { --bg: #111; --text: #eee; }
function toggleTheme() {
const isDark = document.documentElement.dataset.theme === 'dark';
document.documentElement.dataset.theme = isDark ? 'light' : 'dark';
}