JavaScript getComputedStyle() Method: Getting Element Styles

The getComputedStyle() method in JavaScript is a powerful tool that allows you to retrieve the computed CSS styles of any HTML element. Unlike the element.style property, which only returns inline styles, getComputedStyle() provides the final, rendered styles after all style sheets and browser defaults have been applied. This makes it crucial for situations where you need to know the exact appearance of an element, especially when styles are applied through external stylesheets or user-agent defaults.

Understanding the getComputedStyle() Method

The getComputedStyle() method is part of the window object and returns a CSSStyleDeclaration object. This object contains all the CSS properties of the element, including those inherited from parent elements and those defined in external stylesheets. This contrasts with the element.style property which only reflects inline styles directly set on the element.

Purpose of getComputedStyle()

The primary purpose of getComputedStyle() is to provide a way to:

  • Retrieve the final, rendered CSS properties of an element.
  • Inspect styles applied via stylesheets (external, internal), not just inline.
  • Determine the actual visual appearance of an element, taking into account browser defaults and cascading rules.
  • Dynamically adjust or react to the computed styles of elements in your JavaScript code.

Syntax

The syntax for using getComputedStyle() is as follows:

window.getComputedStyle(element, pseudoElement);

Where:

  • element: The HTML element for which you want to retrieve styles.
  • pseudoElement: An optional string specifying a pseudo-element to get styles for (e.g., "::before", "::after"). If not specified, it returns styles for the element itself.

Return Value

The getComputedStyle() method returns a CSSStyleDeclaration object. This object is an array-like structure that you can iterate over, and each property can be accessed by its name. Each style property returns a string value.

Using getComputedStyle(): Practical Examples

Let’s explore some practical examples of how to use getComputedStyle().

Example 1: Getting Basic Styles

In this example, we’ll retrieve and display the computed font-size and color of a paragraph element.

<p id="para1" style="font-weight: bold; color: green;">
  This is a paragraph with some initial inline styles.
</p>

<div id="output1"></div>

<script>
  const para1_element = document.getElementById("para1");
  const output1_div = document.getElementById("output1");

  const computedStyle1 = window.getComputedStyle(para1_element);

  const fontSize1 = computedStyle1.getPropertyValue("font-size");
  const color1 = computedStyle1.getPropertyValue("color");

  output1_div.innerHTML = `
        <p>Computed font-size: ${fontSize1}</p>
        <p>Computed color: ${color1}</p>
    `;
</script>

This is a paragraph with some initial inline styles.

Computed font-size: 16px

Computed color: rgb(0, 128, 0)

Explanation:

  • We use document.getElementById() to get references to the paragraph and output div.
  • window.getComputedStyle(para1_element) retrieves the computed styles for the paragraph element.
  • getPropertyValue() is used to fetch the values of ‘font-size’ and ‘color’.
  • The results are then displayed in the output div. Notice that even though font-weight was set inline, it is not directly returned, only the final render font-size and color is returned.

Example 2: Handling Pseudo-elements

Here, we’ll demonstrate how to get the styles of a pseudo-element using getComputedStyle()

<style>
  #pseudoElement::before {
    content: "::before Content";
    color: blue;
    font-size: 18px;
  }
</style>

<div id="pseudoElement">Main Content</div>
<div id="output2"></div>

<script>
  const pseudoElement_div = document.getElementById("pseudoElement");
  const output2_div = document.getElementById("output2");

  const computedStyle2 = window.getComputedStyle(
    pseudoElement_div,
    "::before"
  );

  const content2 = computedStyle2.getPropertyValue("content");
  const fontSize2 = computedStyle2.getPropertyValue("font-size");
  const color2 = computedStyle2.getPropertyValue("color");

  output2_div.innerHTML = `
        <p>Pseudo content: ${content2}</p>
        <p>Pseudo font-size: ${fontSize2}</p>
        <p>Pseudo color: ${color2}</p>
    `;
</script>
Main Content

Pseudo content: “::before Content”

Pseudo font-size: 18px

Pseudo color: rgb(0, 0, 255)

Explanation:

  • We target the ::before pseudo-element using the second parameter in getComputedStyle().
  • The results show that we can read not only font-size and color, but also the content property of pseudo elements. Note the content is returned as quoted string.

Example 3: Retrieving Margin and Padding

In this example, we’ll retrieve and display the computed margin and padding of a div.

<div id="marginPaddingDiv" style="margin: 20px; padding: 10px; border: 1px solid black; width: 100px;">
  Content with margin and padding.
</div>
<div id="output3"></div>
<script>
  const marginPaddingDiv_element = document.getElementById("marginPaddingDiv");
  const output3_div = document.getElementById("output3");

  const computedStyle3 = window.getComputedStyle(marginPaddingDiv_element);

  const marginTop3 = computedStyle3.getPropertyValue("margin-top");
  const marginRight3 = computedStyle3.getPropertyValue("margin-right");
  const marginBottom3 = computedStyle3.getPropertyValue("margin-bottom");
  const marginLeft3 = computedStyle3.getPropertyValue("margin-left");

  const paddingTop3 = computedStyle3.getPropertyValue("padding-top");
  const paddingRight3 = computedStyle3.getPropertyValue("padding-right");
  const paddingBottom3 = computedStyle3.getPropertyValue("padding-bottom");
  const paddingLeft3 = computedStyle3.getPropertyValue("padding-left");

  output3_div.innerHTML = `
        <p>Margin Top: ${marginTop3}</p>
        <p>Margin Right: ${marginRight3}</p>
        <p>Margin Bottom: ${marginBottom3}</p>
        <p>Margin Left: ${marginLeft3}</p>
        <p>Padding Top: ${paddingTop3}</p>
        <p>Padding Right: ${paddingRight3}</p>
        <p>Padding Bottom: ${paddingBottom3}</p>
        <p>Padding Left: ${paddingLeft3}</p>
    `;
</script>
Content with margin and padding.

Margin Top: 20px

Margin Right: 20px

Margin Bottom: 20px

Margin Left: 20px

Padding Top: 10px

Padding Right: 10px

Padding Bottom: 10px

Padding Left: 10px

Explanation:

  • We retrieve the computed values for all margin and padding properties individually.
  • The results show that you can get all sides of margin and padding with getComputedStyle().

Example 4: Getting the Background Color

This example will retrieve the computed background color for a div element.

<div id="bgColorDiv" style="background-color: lightblue; height: 50px; width: 100px;"></div>
<div id="output4"></div>

<script>
  const bgColorDiv_element = document.getElementById("bgColorDiv");
  const output4_div = document.getElementById("output4");

  const computedStyle4 = window.getComputedStyle(bgColorDiv_element);
  const bgColor4 = computedStyle4.getPropertyValue("background-color");

  output4_div.innerHTML = `<p>Background color: ${bgColor4}</p>`;
</script>

Background color: rgb(173, 216, 230)

Explanation:

  • This code retrieves the computed background-color property which is lightblue. Notice that getComputedStyle() returns the final rendered color which is in rgb() format even though it was set as lightblue.

Browser Compatibility

The getComputedStyle() method is supported by all modern browsers, ensuring cross-browser compatibility.

Browser Version
Chrome All
Firefox All
Safari All
Edge All
Opera All
Internet Explorer 9+

Notes and Important Information

  • element.style vs. getComputedStyle(): Remember that element.style only returns inline styles set directly on the element. Use getComputedStyle() to get the actual rendered styles.
  • Pseudo-elements: Use the second parameter in getComputedStyle() to access the computed styles of pseudo-elements like ::before and ::after.
  • Read-only: The CSSStyleDeclaration object returned by getComputedStyle() is read-only. You cannot use it to set styles on an element.
  • getPropertyValue(): Use getPropertyValue() with the CSS property name (as string) to get the style value.
  • Computed Values: getComputedStyle() will return computed values (e.g. 16px instead of 1em, rgb(0,0,0) instead of black).

Conclusion

The getComputedStyle() method is a critical tool for any JavaScript developer working with web pages. It enables you to obtain the final, rendered styles of HTML elements, including those applied by stylesheets and browser defaults, allowing you to precisely control and respond to your website’s visual appearance. By using this method effectively, you can create dynamic and visually engaging web experiences.