English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Window getComputedStyle() method

JavaScript Window Object

getComputedStyle()The method returns aCSSStyleDeclarationAn object that contains the values of all CSS properties of the element.

The calculated style is the actual style used to display an element after applying styles from multiple sources.

The style source can include: internal style sheets, external style sheets, inherited styles, and browser default styles.

Can be accessed throughCSSStyleDeclarationThe methods provided by the object or accessed by using CSS property names to index into the various CSS property values.

Syntax:

window.getComputedStyle(element, pseudoElement)
var heading = document.getElementsByTagName("h"1")[0];
var x = window.getComputedStyle(heading, null).getPropertyValue("color");
Test and See‹/›

Browser compatibility

The numbers in the table specify the first browser version that fully supports the getComputedStyle() method:

Method
getComputedStyle()11411.559

Parameter value

ParameterDescription
elementThe element for which to get the computed styles
pseudoElement(Optional) A string that specifies the pseudo-element to match. For real elements, omit (or set to null).

Technical details

Return value:A CSSStyleDeclaration object that contains the CSS declaration block of the element, which automatically updates when the element's style changes.

More examples

In this example, we set styles for the <p> element, then use getComputedStyle() to retrieve these styles and print them to the text content of <p>:

let para = document.querySelector('p');
let compStyles = window.getComputedStyle(para);
para.innerHTML = 'font-size: ' + compStyles.getPropertyValue('font-size');
para.innerHTML += '<br>line-height: ' + compStyles.getPropertyValue('line-height');
para.innerHTML += '<br>padding: ' + compStyles.getPropertyValue('padding');
Test and See‹/›

From the element, obtain all the computed styles:

let para = document.querySelector('p');
let compStyles = window.getComputedStyle(para);
for (let i = 0; i < compStyles.length; i++) { 
prop = compStyles.item(i);
txt += prop + " = " + compStyles.getPropertyValue(prop) + "<br>";
}
Test and See‹/›

getComputedStyle() can extract style information from pseudo-elements (such as ::after, ::before, :firstfirst, etc.):

var div = document.getElementsByTagName("div")[0];
var x = window.getComputedStyle(div, "first-letter").getPropertyValue("font-size");
Test and See‹/›

Related References

CSS Tutorial:CSS Tutorial

CSS Tutorial:CSS Pseudo-elements

CSS Reference:CSS Properties

JavaScript Reference:CSSStyleDeclaration Object

CSSStyleDeclaration:getPropertyValue() Method

HTML Reference:HTML Style Properties

HTML Reference:HTML <style> tag

JavaScript Window Object