How to get the value of a CSS property in JavaScript

By

Learn how to read the value of any CSS property in JavaScript with getComputedStyle(), including styles set in an external stylesheet, not just inline ones.

~~~

To read the value of a CSS property in JavaScript, use getComputedStyle(). It’s a global function that returns the final value of every CSS property applied to an element, no matter where that value was defined.

Say you want to fetch the value of a CSS property in a web page, one that is set using a stylesheet.

Your first instinct might be to check the style property of the element. That does not work, because style only lists CSS properties defined in inline styles, or set dynamically from JavaScript.

Not the properties defined in an external stylesheet, which is where most of your CSS lives.

How to use getComputedStyle()

Pass the element to getComputedStyle() and you get back an object with all its resolved properties:

const card = document.querySelector('.product-card')
const style = getComputedStyle(card)

style.backgroundColor //'rgb(255, 255, 255)'
style.fontSize //'16px'

You access properties in camelCase, like backgroundColor for background-color.

Alternatively, you can use getPropertyValue() with the CSS name:

style.getPropertyValue('background-color') //'rgb(255, 255, 255)'

getPropertyValue() is also how you read CSS custom properties:

style.getPropertyValue('--brand-color')

Values come back resolved

Notice that you don’t get back the value as you wrote it in the stylesheet. You get the computed value.

Colors come back in rgb() form even if you wrote a hex value or a keyword like white. Lengths come back in pixels even if you used em or rem. If you set font-size: 1.5rem, reading style.fontSize gives you something like '24px'.

This is a feature. You always get a concrete value you can work with, for example to measure an element before animating it.

Reading pseudo-elements

getComputedStyle() accepts a second argument to inspect pseudo-elements like ::before and ::after:

const style = getComputedStyle(card, '::after')
style.content

There’s no other way to read those styles, since pseudo-elements don’t exist in the DOM.

Be careful with two things

The object you get back is read-only. Trying to assign a value to it fails. To change a style from JavaScript, set it on element.style instead:

card.style.backgroundColor = 'lightyellow'

Also, ask for longhand properties. Some browsers return an empty string when you read a shorthand like margin from the computed style. Read marginTop, marginBottom and so on, and you’ll get a reliable value everywhere.

~~~

Related posts about js: