docs.rodeo

MDN Web Docs mirror

Window: getComputedStyle() method

{{APIRef("CSSOM")}} 

The Window.getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain.

Individual CSS property values are accessed through APIs provided by the returned {{DOMxRef("CSSStyleDeclaration")}}  object, or by indexing with CSS property names. The values returned by getComputedStyle are resolved values.

Syntax

getComputedStyle(element)
getComputedStyle(element, pseudoElt)

Parameters

Return value

A live {{DOMxRef("CSSStyleDeclaration")}}  object, which updates automatically when the element’s styles are changed.

Note that:

The returned object is the same {{DOMxRef("CSSStyleDeclaration")}}  type as the object returned from the element’s {{DOMxRef("HTMLElement/style", "style")}}  property. However, the two objects have different purposes:

Exceptions

Examples

Retrieving computed styles

In this example we style a {{HTMLElement("p")}}  element, then retrieve those styles using getComputedStyle(), and print them into the text content of the <p>.

HTML

<p>Hello</p>

CSS

p {
  width: 400px;
  margin: 0 auto;
  padding: 20px;
  font: 2rem/2 sans-serif;
  text-align: center;
  background: purple;
  color: white;
}

JavaScript

const para = document.querySelector("p");
const compStyles = window.getComputedStyle(para);
para.textContent =
  `My computed font-size is ${compStyles.getPropertyValue("font-size")},\n` +
  `and my computed line-height is ${compStyles.getPropertyValue(
    "line-height",
  )}.`;

Result

{{EmbedLiveSample('retrieving_computed_styles', '100%', '240px')}} 

Use with pseudo-elements

getComputedStyle can pull style info from pseudo-elements (such as ::after, ::before, ::marker, ::line-marker — see the pseudo-element spec).

<style>
  h3::after {
    content: " rocks!";
  }
</style>

<h3>Generated content</h3>

<script>
  const h3 = document.querySelector("h3");
  const result = getComputedStyle(h3, ":after").content;

  console.log("the generated content is: ", result); // returns ' rocks!'
</script>

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN