Episode 37 of 46

Changing CSS Styles

Learn how to modify CSS styles dynamically with JavaScript.

JavaScript can change CSS styles on any element dynamically — great for interactive effects and responsive behaviour.

Inline Styles

let box = document.querySelector(".box");

// Set individual properties (camelCase!)
box.style.backgroundColor = "#3498db";
box.style.color = "white";
box.style.padding = "20px";
box.style.borderRadius = "8px";
box.style.fontSize = "1.2rem";

Note: CSS properties with hyphens use camelCase in JavaScript: background-colorbackgroundColor.

Reading Styles

// Read inline styles
console.log(box.style.backgroundColor);

// Read computed styles (includes CSS file styles)
let computed = window.getComputedStyle(box);
console.log(computed.fontSize);
console.log(computed.margin);

Setting Multiple Styles

// Using cssText (overwrites all inline styles)
box.style.cssText = "background: red; color: white; padding: 20px;";

// Using Object.assign
Object.assign(box.style, {
    background: "#3498db",
    color: "white",
    padding: "20px",
    borderRadius: "8px"
});

Toggle Classes (Better Approach)

Instead of changing styles directly, toggle CSS classes:

// CSS
// .active { background: green; color: white; }
// .hidden { display: none; }

// JavaScript
box.classList.add("active");
box.classList.remove("hidden");
box.classList.toggle("highlight");

This is the recommended approach — keeps styles in CSS and behaviour in JavaScript.