Window getComputedStyle() Method
- Previous Page history
- Next Page innerHeight
- Go to the Previous Level Window Object
Definition and usage
getComputedStyle()
The method retrieves the computed CSS properties and values of an HTML element.
getComputedStyle()
The method returns a CSSStyleDeclaration object.
Computed styles
Computed styles refer to the styles used on an element after all style sources have been applied.
Style sources: external and internal style sheets, inherited styles, and browser default styles.
See also:
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");
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>"; }
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");
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 | A CSSStyleDeclaration object that has all the CSS properties and values of the element. |
The difference between the getComputedStyle() method and the style attribute
Compare the getComputedStyle() method with the HTMLElement's style attribute: the latter only allows access to the inline styles of the element, which can be specified in any unit, and it cannot tell you any information about the styles applied to the element's stylesheet.
Browser Support
All Browsers Support getComputedStyle()
:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Support | 9-11 | Support | Support | Support | Support |
- Previous Page history
- Next Page innerHeight
- Go to the Previous Level Window Object