logo

Getting CSS Styles with JavaScript

September 5, 2021

There are two possible ways to get CSS values in JavaScript, depending on if you are trying to get the inline styles or the computed styles.

Getting inline styles

Inline styles are the styles that are present in the HTML in the style attribute.

<h1 style="margin-top: 3rem; background-color: lightgrey">I am h1</h1>

To get the inline styles applied to a specific element, you can use the style property.

const h1Elem = document.querySelector("h1");

const marginTop = h1Elem.style.marginTop;
console.log(marginTop); // 3rem

const backgroundColor = h1Elem.style.backgroundColor;
console.log(backgroundColor); // lightgrey

Getting computed styles

If you also add styles to this element in your CSS file, you will need to get the computed styles using the getComputedStyle property.

h1 {
  color: tomato;
  font-size: 3em;
  border: 1px solid;
}

h1::before {
  content: "•";
}

If we use the style property to get the color applied to the h1 element we will get: "", even if we gave the h1 element a tomato color. The same happens with any property we did not set an inline style.

const h1Elem = document.querySelector("h1");
console.log(h1.style.color); // ""
console.log(h1.style.fontSize); // ""
console.log(h1.style.border); // ""

We can use getComputedStyle method to find out the actual styles applied to the h1 element. If you set a property in relative units like rem or em, getComputedStyle will return the value you set but in px.

console.log(getComputedStyle(h1.color)); // "rgb(255, 99, 71)" (tomato color but an RGB color)
console.log(getComputedStyle(h1.fontSize)); // "48px" (font-size but in px)
console.log(getComputedStyle(h1.border)); // "1px solid rgb(255, 99, 71)"

If you log getComputedStyle(h1), you should see an object that contains every CSS property and its respective values:

getComputedStyle(h1) image

As a side note getComputedStyle(Element [, pseudoElement]) method takes in two values:

  • The first value is the element you've selected with the querySelector method;
  • pseudoElement which refers to the string of the pseudo-element you're trying to get (if it is not omitted).

Getting styles from pseudo-elements

To get the style from a pseudo-element, you will need to pass in a string with the pseudo-element as the second argument to the getComputedStyle method.

console.log(getComputedStyle(h1, "::before").content); // ""•""