JavaScript Reference ยท DOM: Document and Elements
window.getComputedStyle()
Reference for getComputedStyle(): read the final CSS values the browser applies to an element, including pseudo-elements, custom properties and resolved units.
The getComputedStyle() function returns an object holding the final CSS values of an element, after the browser has applied style sheets, inheritance, the cascade and relative units. Unlike element.style, which shows only inline declarations, it tells you what the user actually sees.
The result is read-only and live: if the element's styles change later, the same object reflects the new values. To change a style, write to element.style or switch a class.
const styles = getComputedStyle(element); styles.color; // "rgb(255, 99, 71)" styles.getPropertyValue("font-size");
Try it
Syntax
getComputedStyle(element) getComputedStyle(element, pseudoElement)
| Name | Description |
|---|---|
element |
The element to inspect. |
pseudoElement |
Optional. A pseudo-element selector string such as "::before", "::after" or "::first-line". |
Return value: a read-only CSSStyleDeclaration. Read values as camelCase properties (cs.fontSize) or with getPropertyValue("font-size").
Exceptions: TypeError if element is not an element (for example null from a failed query).
Usage notes
- Resolved values. Colours are returned as
rgb(...)orrgba(...)strings, and lengths such asem,remand%forwidthorheightcome back as pixels once the element has been laid out. Shorthand properties may be empty or normalized differently across browsers, so read the longhands (padding-top,border-top-width) instead. - Elements that are not rendered. With
display: noneor when detached, properties likewidthreturn the computed (not used) value, such asautoor50%. - Triggers style or layout work. Reading values may force the browser to recalculate styles, and sizes may force layout. Avoid alternating reads and writes in a loop.
- During transitions. The values reflect the current mid-transition state.
- Custom properties.
getPropertyValue("--name")returns the declared value as text. Trim it before comparing, since leading whitespace may be kept. window.prefix.getComputedStyle()is a method ofwindow, so the prefix is optional in browsers.- Visited links. For privacy, browsers return values as if a link was unvisited.
- Layout measurements. For the box size and position,
getBoundingClientRect()is usually better than parsing strings from computed styles.
Browser support
Supported in every browser. The optional pseudo-element argument is supported too; modern browsers accept it in the ::before form.
Related
HTMLElement.styleโ set inline stylesElement.getBoundingClientRect()โ size and positionElement.classListโ switch style rules- Lesson: Styles and classes