Window getComputedStyle()
Example
Get the computed background color of an element:
const element = document.getElementById("test");
const cssObj = window.getComputedStyle(element, null);
let bgColor = cssObj.getPropertyValue("background-color");
Try it Yourself »
More examples below.
Description
The getComputedStyle()
method gets the computed CSS properties and values of an HTML element.
The getComputedStyle()
method returns a
CSSStyleDeclaration object
.
Computed Style
The computed style is the style used on the element after all styling sources have been applied.
Style sources: external and internal style sheets, inherited styles, and browser default styles.
See Also:
Syntax
window.getComputedStyle(element, pseudoElement)
Parameters
Parameter | Description |
element | Required. The element to get the computed style for. |
pseudoElement | Optional. A pseudo-element to get. |
Return Value
Type | Description |
An object | A CSSStyleDeclaration object with all the CSS properties and values of the element. |
More Examples
Get all the computed styles from an 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 »
Get computed font size of the first letter in an element (using pseudo-element):
const element = document.getElementById("test");
const cssObj = window.getComputedStyle(element, ":first-letter")
let size = cssObj.getPropertyValue("font-size");
Try it Yourself »
Browser Support
getComputedStyle()
is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.