Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a function return *just* an rgba value?

Tags:

less

I was storing rgba values as variables (eg: @black: rgba(0, 0, 0, 1.0);) and i realized it would be nice if i could make the alpha value variable.

So, i tried this..

.color_black (@alpha: 1.0) { rgba(0, 0, 0, @alpha) }

The problem is simply that this does not work. The parameter section seems to be right, infact it only seems to "break" once you add in the rgba() code. Less really doesn't like the rgba call.

Now i can make this work by defining the property tag, for example..

.color_black (@alpha: 1.0) { color: rgba(0, 0, 0, @alpha) }

But this sort of defeats the usefulness of storing a single color, and reusing it all over town. In backgrounds, texts, gradients, etc.

So, any thoughts on how to fix this?

edit: While i am not happy with this either.. this is the best solution i can come up with..

.color_black (@prop: color, @alpha: 1.0) { @prop: rgba(0, 0, 0, @alpha) }

It's not as useful of a function, as you can't use it in other properties (gradients, etc). Thoughts?

like image 253
Lee Olayvar Avatar asked Jan 20 '26 14:01

Lee Olayvar


2 Answers

Take a look at less's color-functions: http://lesscss.org/#-color-functions

I think 'fade' is what you're looking for. Just set your color as a variable...

@black: #000000;

...and use fade():

color: fade(@black, 80%);
like image 112
Claudio Albertin Avatar answered Jan 23 '26 21:01

Claudio Albertin


You faced this issue probably because rgba() is an internal function in less; so is hsla().

To use the mixin as a function that sets a variable as desired, you'd need to use mixins as functions feature, like below:

// mixin
.toRGBA( @color, @alpha) { 
  @color_plus_alpha: rgba(red(@color), green(@color), blue(@color), @alpha); //[A]
}


// usage
.someClass {
  .toRGBA(orange, 0.3); // [B]
  color: @color_plus_alpha; // [C]
}

The catch here is the added line [B], and the fact that you'd always need to use the variable @color_plus_alpha in [C] that is defined in the mixin on line [A].

This works at the time of this edit, and outputs the following:

.someClass {
  color: rgba(255, 165, 0, 0.3);
}

However, this still does not let you assign the "output" of the mixin to an arbitrary variable as the OP desires.

Note that, red(), green() and blue() are also internal functions that spit out respectively the red, green and blue components of the input color.

Edit: Updated the answer to be a bit more reusable. The previous version would have only worked for a hard-coded property name color.

like image 42
lost-and-found Avatar answered Jan 23 '26 20:01

lost-and-found