How to convert HEX color to rgba with Less compiler?

I have the following code:

@color : #d14836;

.stripes span {
-webkit-background-size: 30px 30px;
-moz-background-size: 30px 30px;
background-size: 30px 30px;
background-image: -webkit-gradient(linear, left top, right bottom,
                    color-stop(.25, rgba(209, 72, 54, 1)), color-stop(.25, transparent),
                    color-stop(.5, transparent), color-stop(.5, rgba(209, 72, 54, 1)),
                    color-stop(.75, rgba(209, 72, 54, 1)), color-stop(.75, transparent),
                    to(transparent));

I need to convert @color to rgba(209, 72, 54, 1) .

So I need to replace rgba(209, 72, 54, 1) in my code with Less function that generates rgba() value from my @color variable.

How can I do this with Less?


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 dont need a alpha key you can simply use the hex representation of the color. A rgba color with a alpha of '1' is the same as the hex 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: none9; // Only IE8
    filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d')", argb(@rgba-color),argb(@rgba-color))); // IE9 and down
    // Problem: Filter gets applied twice in IE9.
    // 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.

链接地址: http://www.djcxy.com/p/15800.html

上一篇: 在将不透明度应用于表单时,我们应该使用小数还是双精度值?

下一篇: 如何使用少编译器将HEX颜色转换为rgba?