If I set the alpha value via rgba(r, g, b, a) in javascript to anything other than 1, the actual value set by browser is slightly different. But value set in CSS is an exact match.
See code sample in code-pen-site
<head>
<script type="text/javascript" language="javascript">
window.onload=function() {
document.getElementById("p1").style["background-color"]="rgba(255,0,0,0.3)";
}
</script>
</head>
<body>
<p>RGB colors with opacity:</p>
<p id="p1">Red</p>
<p id="p2">Green</p>
</body>
Why if CSS color is set via Javascript then the number changes?
RGBA color values are an extension of RGB color values with an alpha channel - which specifies the opacity for a color. An RGBA color value is specified with: rgba(red, green, blue, alpha). The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).
In CSS, a color can be specified as an RGB value, using this formula: rgb(red, green, blue) Each parameter (red, green, and blue) defines the intensity of the color between 0 and 255. For example, rgb(255, 0, 0) is displayed as red, because red is set to its highest value (255) and the others are set to 0.
The <alpha-value> CSS data type represents a value that can be either a <number> or a <percentage> , specifying the alpha channel or transparency of a color.
The alpha component specifies the transparency of the color: 0 is fully transparent, and 255 is fully opaque. Likewise, an A value of 255 represents an opaque color. An A value from 1 through 254 represents a semitransparent color. The color becomes more opaque as A approaches 255.
First, my original observation is incorrect. If you click on the "Computed" tab to inspect the background-clor, this difference is observed for both CSS rules inside 'style' tag and inline within elements. I
In chromium source code this implementation explains the 0.001961 difference in the alpha value
// Convert the floating pointer number of alpha to an integer in the range [0, 256),
// with an equal distribution across all 256 values.
int alphaComponent =
static_cast<int>(
clampTo<double>(alpha, 0.0, 1.0) * nextafter(256.0, 0.0));
Here if alpha is 0.3, then alphaComponent becomes 0.298039. (If I set alpha to any floating point in [0.0, 1.0] the number shown by webInspector matches the alphaComponent value acquired from above formula.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With