Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getComputedStyle gives "transparent" instead of 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. However

window.getComputedStyle(h1).backgroundColor

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

The element I call h1 is visible on the screen. I was expecting to get the actual background color. The value I get above (in rgba) is not wrong, but not very useful either. It just tells me the background is fully transparent - and that is not a color.

How do I get the actual background color in RGB?

like image 433
Leo Avatar asked Apr 05 '14 03:04

Leo


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.

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

like image 65
Stijn Heylen Avatar answered Nov 16 '22 13:11

Stijn Heylen


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

Which means you can get those css value only which applied to particular element in any way.

Eg:- if you applied background for h1 :RGB{255, 255, 255}, then you will get the background color white in rgb format otherwise not. It does not provide value for html's default style.

To get the value by getComputedStyle(), First you should apply this to element.

For more info getComputedStyle()

like image 42
Suman Bogati Avatar answered Nov 16 '22 11:11

Suman Bogati