Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the exact RGBa value set through CSS via Javascript?

In most browsers I've tried, rgba() values seem to be changed once the browser parsed the CSS.

For example, the following CSS:

background-color: rgba(255, 0, 0, 0.5);

Gives the following CSS value when accessed via jQuery.css('background-color') or native CSSStyleDeclaration.getPropertyValue('background-color'):

rgba(255, 0, 0, 0.498039)

Here's a fiddle with more examples.

Chrome and Safari give different results. Firefox seems to be the only browser that reports the exact value as entered. Is this a bug or by design?

like image 422
Vlad Magdalin Avatar asked Dec 06 '12 23:12

Vlad Magdalin


1 Answers

Mark Hubbart's comment is correct.

32-bit color breaks down into four 8-bit components, each within the range 0-255: red, green, blue, and alpha. We express the alpha, or transparency, as a fraction or percentage since it helps us decimal-brained folks get a quicker idea of just how transparent it is. It is actually better thought of as opaqueness (well, opacity) since 100% transparent is 0, not 1.

Now, given 255 is the denominator for the alpha value, there is no way to express 0.5 exactly. The value you're seeing, 0.498039, comes from the nearest fraction, 127/255 (rounded to 6 decimal places). Safari returns 0.496094 which is 127/256 rounded to 6 decimal places, and to me seems a bug since that implies 257 values. I also doubt Firefox can accurately report 0.5 unless it is rounding to only 2 decimal places.

You can work around this issue in different browsers by creating a jQuery plugin that, on first execution, checks to see what value is returned with a 50% alpha, and adjust all calculations accordingly.

parseFloat(
   $('#divWith50PercentAlphaBackgroundStyle')
      .css('background-color')
      .split(',')[3],
   10
)

Then, with this value in hand, do a switch on it against the values different browsers return, and properly convert to the closest correct value you're expecting.

like image 185
ErikE Avatar answered Oct 01 '22 20:10

ErikE