Méthode getComputedStyle()

Definition and usage

getComputedStyle() The method retrieves the computed CSS properties and values of the HTML element.

getComputedStyle() The method returns a CSSStyleDeclaration object.

Computed styles

Computed styles refer to the styles used on the element after all style sources have been applied.

Style sources: external and internal style sheets, inherited styles, and browser default styles.

See also:

Objet CSSStyleDeclaration

Instance

Example 1

Get the computed background color of the element:

const element = document.getElementById("test");
const cssObj = window.getComputedStyle(element, null);
let bgColor = cssObj.getPropertyValue("background-color");

Try it yourself

Example 2

Get all computed styles from the element:

const element = document.getElementById("test");
const cssObj = window.getComputedStyle(element, null);
let text = "";
for (x in cssObj) {
  cssObjProp = cssObj.item(x)
  text += cssObjProp + " = " + cssObj.getPropertyValue(cssObjProp) + "<br>";
}

Try it yourself

Example 3

Get the computed font size of the first letter in the element (using a pseudo-element):

const element = document.getElementById("test"); const cssObj = window.getComputedStyle(element, ":first-letter")
let size = cssObj.getPropertyValue("font-size");

Try it yourself

Syntax

window.getComputedStyle(element, pseudoElement)

Parameter

Parameter Description
element Required. The element for which to retrieve the computed styles.
pseudoElement Optional. The pseudo-element to be retrieved.

Return value

Type Description
Object CSSStyleDeclaration object that has all the CSS properties and values of the element.

Difference between getComputedStyle() method and style attribute

Compare the getComputedStyle() method with the HTMLElement's style attribute: the latter only allows access to the inline styles of the element, with any unit you specify, and it cannot tell you any information about the styles applied to the element's stylesheet.

Support des navigateurs

Tous les navigateurs prennent en charge getComputedStyle()

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support