On this page
The example code and the keyboard below it.

How to get the actual (real) background color of an HTML element

Learn how to get the actual background color of an HTML element, even if it's transparent or inherited from a parent element.

In many browsers, when no explicit background color is set for the <html> or <body> elements, they inherit a transparent background.

However, browsers often render the default background as white for visual consistency, particularly in user interfaces where a clear background is expected. This can lead to confusion when using JavaScript to check computed styles.

Why does the page have a transparent background color by default, even though browsers display a white background?

The html element inherits its background color from the user agent stylesheet, which is usually set to transparent. The body element inherits this transparent background color from the html element. Browsers then apply their default white background color to the viewport, which is separate from the document content.

Why getComputedStyle returns transparent value?

The reason getComputedStyle returns transparent instead of white is because the getComputedStyle method reflects the actual computed style of an element based on CSS rules applied to it.

Since no explicit background color is set on the html or body elements, their computed style remains transparent. The visible white color comes from the viewport background, not from an element’s computed style.

Demonstrating the behavior

Here’s a simple example to illustrate this behavior:

HTML with all default browser styles
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Background color test</title>
    <style>
        /* No background color set */
    </style>
</head>
<body>
    <script>
        console.log(window.getComputedStyle(document.documentElement).backgroundColor); // transparent
        console.log(window.getComputedStyle(document.body).backgroundColor); // transparent
    </script>
</body>
</html>

In this example, even though you’ll see a white background when viewing the page, both getComputedStyle calls will return transparent value.

How to get the visible, real background color

If you need to determine the actual visible background color of the element, e.g., html, body, you can use the following technique:

HTML with all default browser styles
function getRealBackgroundColor(element) {
  const rootElement = element || document.documentElement;
  const originalBackgroundColor = window.getComputedStyle(rootElement)?.getPropertyValue("background-color");

  rootElement.style.setProperty("background-color", "Window");

  const realColor = window.getComputedStyle(rootElement)?.getPropertyValue("background-color");

  if (typeof originalBackgroundColor === "string") {
    rootElement.style.setProperty("background-color", originalBackgroundColor);
  }

  if (realColor === undefined) {
    return "rgba(0, 0, 0, 0)";
  }

  return realColor;
}

console.log(getRealBackgroundColor());

This function temporarily changes the background color to the system’s window color in order to determine the real visible background color, and then returns the original color.

The Window refers to the background color of the browser window. So, the element is essentially inheriting the background color of the browser window, commonly seen as white background. If you were to change the browser window’s background color to a different color, the element would inherit that color as well.

For more accurate results, especially in complex layouts, you might need to traverse up the DOM tree and check for any non-transparent backgrounds.

Workable example that determines background color for HTML root element

Use cases for finding real background color

Finding the real rendered background color is particularly useful for accessibility and calculating contrast between text color and background color.

However, there are more cases related to web development and design.

  1. Dynamic UI elements: in applications with dynamic content, such as dashboards or media websites, knowing the background color helps ensure that text and other UI elements remain readable. For instance, if a card component changes its background color based on user interaction, determining the current background color is essential for maintaining visual accessibility.
  2. Theming and customization: when implementing themes or user-customizable interfaces, developers need to retrieve the effective background color to apply complementary styles dynamically. This is particularly relevant in dark mode implementations where the background can change based on user preferences.
  3. Data visualization: in data visualization tools, the background color can significantly affect how data is perceived. Designers often need to assess the real background color to ensure that chart elements stand out against it. For example, a bright chart on a dark background may need adjustments to maintain clarity and focus on data points.
  4. Testing and automation: automated testing frameworks (like Puppeteer) often require verification of UI elements’ styles, including background colors. This ensures that the application behaves as expected across different browsers and devices, facilitating consistent user experiences.
  5. Accessibility compliance: ensuring that web applications meet accessibility standards involves checking contrast ratios between text and background colors. By finding the real background color, developers can verify compliance with guidelines like WCAG (Web Content Accessibility Guidelines), which mandate certain contrast levels for readability.
  6. Debugging layout issues: when troubleshooting layout problems or unexpected visual behaviors in web applications, developers may need to determine the effective background color of elements to understand how they interact with other components visually.
  7. Cross-browser consistency: different browsers may render default styles differently (e.g., default background colors). Knowing the actual background color helps developers create consistent experiences across various platforms.

Best practices

  • Always set explicit background colors on the <html> or <body> elements if you want to control the page background color reliably.
  • Use CSS custom properties (variables) to manage colors consistently across your site.
  • Be aware of browser defaults and how they interact with inherited styles when designing your layout.

Remember, the behavior you’re observing is standard across modern browsers and is part of how they handle default styles and inheritance. By understanding this behavior, you can design your stylesheets more effectively and avoid unexpected visual outcomes.

Related posts

Comments

Leave a Reply

Search in sitelint.com

Looking for automated testing for technical SEO?

With SiteLint, you can help search engine spiders crawl and index your site more effectively.

Real-user monitoring for Accessibility, Performance, Security, SEO & Errors (SiteLint)