When using getComputedStyle, it is expected to return the final computed CSS property value. However, for background-color, browsers tend to return "transparent" (or rgba(x,x,x,0)) instead of computing the inherited value from ancestors.
The method only seems to work when the element has a background color specifically defined (even if through its class, but not through the parent's definitions). This limitation makes getComputedStyle somewhat useless since it should consider all ancestor's definitions.
Interestingly, the method works properly for other properties like color, as demonstrated in the fiddle.
Is there a way to accurately determine the effective background color of an element using JavaScript, rather than being consistently told that it is transparent?
let para = document.querySelector('p');
let compStyles = window.getComputedStyle(para);
para.textContent = 'Incorrect background-color: ' + compStyles.getPropertyValue('background-color') + ', but font color is correct: ' + compStyles.getPropertyValue('color');
/* no colors are specified for p */
p {
width: 400px;
margin: 0 auto;
padding: 20px;
line-height: 2;
font-size: 2rem;
font-family: sans-serif;
text-align: center;
}
/* this is the important part, only color gets inherited, not background-color */
div {
background-color: purple;
color: lightblue;
}
<!-- Original example taken from MDN: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle -->
<div>
<p>Hello</p>
</div>
If helpful, the X question could be: How can I calculate the color luminosity difference between font color and background for each element on a page within a user script? ;) The limitations of getComputedStyle may make this task challenging, but it remains an intriguing question nonetheless.