Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a hexadecimal color to rgba with the Less compiler?

Tags:

css

less

People also ask

Can I use hex in RGBA?

In CSS, there are several formats for colors that can be used. Common ones include hex (hexadecimal) codes, RGB (red, green, blue), RGBA (red, green, blue, alpha), and HSL (hue, saturation, lightness).

What does RGBA 255 0 0 0.2 color code in CSS means?

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. To display black, set all color parameters to 0, like this: rgb(0, 0, 0).

How is RGBA color calculated?

To get the percentage equivalent, simply divide the integer by 255 and then multiply by 100%. Going off the previous example, if the RGBA color value is rgba(255, 242, 0, 0.5) then: Red: (255/255) x 100% = 100% Green: (242/255) x 100% = 94.9%


Actually, the Less language comes with an embedded function called fade. You pass a color object and the absolute opacity % (higher value means less transparent):

fade(@color, 50%);   // Return @color with 50% opacity in rgba

If you don't need an alpha key, you can simply use the hexadecimal representation of the color. An rgba color with a alpha of '1' is the same as the hexadecimal value.

Here are some examples to demonstrate that:

@baseColor: #d14836;

html {
    color: @baseColor;
    /* color:#d14836; */
}

body {
    color: rgba(red(@baseColor), green(@baseColor), blue(@baseColor), 1);
    /* color:#d14836; */
}

div {
    color: rgba(red(@baseColor), green(@baseColor), blue(@baseColor), 0.5);
    /* rgba(209, 72, 54, 0.5); */
}

span {
    color: fade(@baseColor, 50%);
    /* rgba(209, 72, 54, 0.5); */
}

h3 {
    color: fade(@baseColor, 100%)
    /* color:#d14836; */
}

Test this code online: http://lesstester.com/


My Less mixin:

.background-opacity(@color, @opacity) {
    @rgba-color: rgba(red(@color), green(@color), blue(@color), @opacity);

    background-color: @rgba-color;

    // Hack for IE8:
    background: none\9; // Only Internet Explorer 8
    filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d')", argb(@rgba-color),argb(@rgba-color))); // Internet Explorer 9 and down
    // Problem: Filter gets applied twice in Internet Explorer 9.
    // Solution:
    &:not([dummy]) {
      filter: progid:DXImageTransform.Microsoft.gradient(enabled='false'); // Only IE9
    }
}

Try it.

EDITED: As seen on rgba background with IE filter alternative: IE9 renders both!, I added some lines to the mixin.


It seems that with the recent Less update 3.81, you can use just two arguments in the rgba() function.

rgba(white, 0.3) or rgba(white, 30%) => rgba(255, 255, 255, 0.3)

It works for me, but I can't find it in the official documentation.