Freigeben über


CSS3 Colors–RGBA vs. HSLA

hslThere really is no battle between RGBA and HSLA.  Either can accomplish the task of discovering the color that is just right for you.  Which should you choose?  Which is an easier concept for you to understand?

Red
Green
Blue

Hue
Saturation
Lightness

Alpha (opacity)

 

Again, which above is easier for you to understand?

According to the W3C:

4.2.4. HSL color values

CSS3 adds numerical hue-saturation-lightness (HSL) colors as a complement to numerical RGB colors. It has been observed that RGB colors have the following limitations:

  • RGB is hardware-oriented: it reflects the use of CRTs.
  • RGB is non-intuitive. People can learn how to use RGB, but actually by internalizing how to translate hue, saturation and lightness, or something similar, to RGB.

Is RGB truly non-intuitive?  By looking at the color wheel in this post would it be intuitive for you to know the hue value of 1 or 360 is red?  Which is easier to digest:  blue=blue or 240=blue.

It doesn’t really matter.  What really mattered to me was to understand the algorithm to convert from one to another.  Since alpha is simply a scale of opacity, I was more curious about the conversion of red, green, and blue to something light, saturated, and with hue.

To test my understanding, I set out to write a script that was CSS3 friendly.  In other words, it would use as inputs/outputs values used in the rgba() and hsla() functions in CSS3.  The result is the script below. 

As always, I value feedback Smile

 // elsewhere in script use this way:
// var result = Palermozr.rgbToHsl(255,255,255);
 // result.H // Hue (between 1 and 360)
 // result.S // Saturation (between 0 and 100) %
 // result.L // Lightness (between 0 and 100) %
var Palermozr= (function () {
    function rgbToHsl(r, g, b) {
        r /= 255;g /= 255;b /= 255;
        var max = Math.max(r, g, b),
            min = Math.min(r, g, b);
        var d = max - min,
            u = max + min;
        var h = 0, s = 0, l = u / 2;
        if (d !== 0) {
            s = l < 0.5 ? d / u : d / (2 - d);
            var rr = (((max - r) / 6) + (max / 2)) / d;
            var gg = (((max - g) / 6) + (max / 2)) / d;
            var bb = (((max - b) / 6) + (max / 2)) / d;
            switch (max) {
                case r: h = (bb - gg); break;
                case g: h = (1 / 3) + (rr - bb); break;
                case b: h = (2 / 3) + (gg - rr); break;
            }
            if (h < 0) h += 1;
            if (h > 1) h -= 1;
            h = Math.round((h * 360));
        }
        s = Math.round(s * 100);
        l = Math.round(l * 100);

        // returns object with H,S, and L property values
        return { H: h, S: s, L: l };
    }
    
    return {
        rgbToHsl: rgbToHsl
    };
})();