JavaScriptDOM and events

HTMLElement.style

An object of styles set directly on an element (inline), for reading and changing individual CSS properties.

Returns
A CSSStyleDeclaration object with the element’s inline styles.
On this page

Example

#
JavaScript
const bar = document.querySelector('#bar')

bar.style.width = '65%'
bar.style.backgroundColor = 'orange'

console.log(bar.style.width)
console.log(bar.style.backgroundColor)
console.log(bar.style.height)
Console
65%
orange
12px

Definition and usage

#

The style property gives you access to the styles stored in the element’s style attribute. Every CSS property has a camelCase counterpart here: background-color is style.backgroundColor, and font-size is style.fontSize. You set values as strings, always with a unit, e.g. "200px".

style only shows inline styles. You won’t see rules from stylesheets in it, so reading style.color for an element styled by a class returns an empty string. To read the actual, computed appearance, use the getComputedStyle(element) function.

You can set CSS variables (e.g. --accent) with the style.setProperty("--accent", "#7c3aed") method, and remove a style by assigning an empty string or calling removeProperty(). For bigger visual changes, it’s better to toggle classes through classList, and leave style for values computed on the fly, such as the position or width of a progress bar.

Syntax

#
Syntax
element.style.propertyName = value
element.style.setProperty(name, value)
element.style.removeProperty(name)

getComputedStyle(element).propertyName

More examples

#
style only sees inline styles
JavaScript
const title = document.querySelector('#title')

console.log(title.style.color === '')
console.log(getComputedStyle(title).color)
console.log(getComputedStyle(title).fontSize)
Console
true
rgb(167, 139, 250)
20px
CSS variables and units
JavaScript
const box = document.querySelector('#box')

box.style.setProperty('--accent', '#0ea5e9')
console.log(box.style.getPropertyValue('--accent'))

box.style.width = 120
console.log(box.style.width === '')

box.style.width = '120px'
console.log(box.style.width)
Console
#0ea5e9
true
120px

Assigning the plain number 120 is ignored, since CSS requires a unit for width. Only the string "120px" changes the style.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Always include a unit: style.width = "120px". A plain number is ignored.
  • To read styles from stylesheets, use getComputedStyle(element), since style only sees inline values.
  • Describe bigger visual changes in CSS as a class, and toggle it through classList.

Related entries

#

Spotted a mistake or missing an example? Write to us.