GetComputedStyle gives a "transparent" instead of the actual background color

This was a surprise. The following code does not seem to give me the actual colors on the screen:

h1 = document.querySelector("h1"); window.getComputedStyle(h1).color 

Gives rgb(0, 0, 0) which I think is correct. but

 window.getComputedStyle(h1).backgroundColor 

gives rgba(0, 0, 0, 0) . The actual background color that I see on the screen is white.

The element that I call h1 is displayed on the screen. I expected to get the actual background color. The value I get above (in rgba) is not wrong, but not very useful. He just tells me that the background is completely transparent - and that is not the color.

How to get the actual background color in RGB?

+6
javascript html background-color css
source share
2 answers

If you set your background color: rgba (255, 255, 255, 0 ) in your css; getComputedStyle() will return transparent (in some browsers) instead of your rgba value.

An easy fix for this is setting alpha to something greater than 0, for example rgba (255, 255, 255, 0.01 ); This will return rgba (255, 255, 255, 0.01 )

+4
source share

getComputedStyle(h1) provides the css value of the element after being applied to the active stylesheet.

This means that you can get a css value that applies only to a specific element.

For example: if you applied the background to h1 :RGB{255, 255, 255}, , then you will get a white background color in rgb format, otherwise not. It does not provide default HTML style values.

To get getComputedStyle() , you must first apply it to the element.

For more information getComputedStyle ()

+1
source share

All Articles