简体   繁体   中英

LESS CSS preprocessor: Is there a way to map a single color to an rgb and rgba definition?

I'm trying to write a block in the CSS preprocessor LESS that will do the following:

@transparent_background(@color; @alpha: .8)
{
  background: @color;
  background: rgba(<color R value>, <color G value>, <color B value>, @alpha);
}

Is there any way to get the RGB values out of @color if it's a standard hex definition (ie #rrggbb)? Is there a way to do this if @color is defined some other way?

EDIT: SOLUTION

@transparent_background(@color; @alpha: .8)
{
  background: @color;
  background: @color + rgba(0, 0, 0, @alpha);
}

Try this:

background: @color - rgba(0, 0, 0, 1.0) + rgba(0, 0, 0, @alpha);

The subtraction will clear the alpha channel on @color then you just add the desired @alpha to the alpha channel. Colors have the full suite of operators and they work component by component when operating on two colors; colors are stored as RGBA components internally so this should work. Also, the alpha channel is normalized to be in the interval [0, 1.0] so subtracting 1.0 from the alpha channel should clear it without causing any problems.

I don't have CSS LESS set up right now so I can't check but this is worth a shot.

I know this is an old question, but if all you are looking to do is add an alpha value just use fade(@color, @alpha) . Color can be in hex, rgba or hsla.

None of the solutions work anymore, but this one does (thanks to @Elyse ):

.alpha(@color, @alpha: 0.8) {
    color: @color;
    color: hsla(hue(@color), saturation(@color), lightness(@color), @alpha);
}

The hsla() function, while not advertised in the LESS website, is defined in the source code .

Note that you can also proceed with the fadein/fadeout functions of LESS :

.alpha(@color, @alpha: 80)
{
    background-color: fadeout(@color, (100 - @alpha));
}

Thus, .alpha(red, 25) will result in a background-color of rgba(255, 0, 0, 0.25)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM