Syntax
element.style.propertyName = value;
getComputedStyle(element).propertyNameExamples
Setting Inline Styles Directly
Reading and writing an element's own inline style properties.
const box = document.querySelector("#box");
box.style.backgroundColor = "blue";
box.style.width = "200px";
box.style.fontSize = "1.5rem"; // camelCase for hyphenated CSS properties
console.log(box.style.backgroundColor); // "blue" - only reflects inline styles set this waygetComputedStyle() - The Real Rendered Value
Getting the actual applied style, regardless of where it came from (CSS file, class, or inline).
// Even if color is set via an external CSS class, not inline:
const box = document.querySelector("#box");
const styles = getComputedStyle(box);
console.log(styles.color); // the actual rendered color, from any source
console.log(styles.fontSize); // always returns a computed pixel value, like "16px"
console.log(box.style.color); // "" - empty, since color was not set inlineBest practices
- Use element.style for styles your own script sets directly - use CSS classes with classList for styles that come from a stylesheet
- Use getComputedStyle() when you need to read the actual current visual value of a property, no matter its source
- Remember getComputedStyle() returns resolved values (like pixels), not the original units used in the stylesheet (like rem or %)
- Prefer toggling CSS classes over directly setting element.style in application code, for cleaner separation between structure/behavior and presentation
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification