Labithiotis
Labithiotis

Reputation: 4149

LESS Mixin/Function to change a @Color HEX to RGBA to PASS into another mixin

I want to convert a base color in HEX (@color) to rgba and use that in a mixin like .box-shadow(x y b color);

I have seen a load of mixins to convert HEX to RGBA and set background-color, and I know I can create my own mixing for box-shadow. But is there a generic solution so we can use any existing mixin.

Tried/want something like this (doesn't work) :

/** Extend LESS functions like (lighten, darken, mix) **/
rgbaColorIn(@color, @opacity : 1){
  return rgba( red(@color), green(@color), blue(@color), @opacity );
}

// ----- or ------

/** Passing in a reference to mixin and params **/
.rgbaColorIn(@selector, @params, @color, @opacity : 1){
  @rgbaColor: rgba( red(@color), green(@color), blue(@color), @opacity );
  @selector(@params @color);
}

Upvotes: 4

Views: 13132

Answers (3)

helderdarocha
helderdarocha

Reputation: 23627

There is no return keyword in less. If you want a mixin that returns a value, then you can define a variable inside it, for example:

.rgbaColorIn(@color, @opacity : 1){
  @result: rgba( red(@color), green(@color), blue(@color), @opacity );
}

which you can access in the scope you call the mixin:

.section {
  .rgbaColorIn(red, 50%);
  background-color: @result;
}

But if you just want to generate a RGBA from a RGB color, you can use the fade function:

.section {
  @result: fade(red, 50%);
  background-color: @result;
}

which will render the same result in CSS:

.section {
  background-color: rgba(255, 0, 0, 0.5);
}

A .box-shadow mixin to pass the RGB color and opacity/alpha separately could be something like this:

.box-shadow(@x; @y; @b; @color; @opacity) {
   box-shadow: @x @y @b fade(@color, @opacity);
   -moz-box-shadow: @x @y @b fade(@color, @opacity);
   -webkit-box-shadow: @x @y @b fade(@color, @opacity);
}

Which you could use in a selector like this:

.section {
  .box-shadow(2px; 2px; 1px; pink; 50%);
}

and obtain this CSS:

.section {
  box-shadow: 2px 2px 1px rgba(255, 192, 203, 0.5);
  -moz-box-shadow: 2px 2px 1px rgba(255, 192, 203, 0.5);
  -webkit-box-shadow: 2px 2px 1px rgba(255, 192, 203, 0.5);
}

Upvotes: 26

Mattos
Mattos

Reputation: 447

Good answers, I guess you also could do directly calling a box-shadow cross-browser function:

.toShadow(@color: red) {
  @color-rgba: rgba(red(@color), green(@color), blue(@color), .6);
  .box-shadow(~"inset 0 0 3px @{color-rgba}");
}

Upvotes: 1

ScottS
ScottS

Reputation: 72271

To get an rgba value (assuming you are giving it something other than 100% opacity, since LESS will just keep it as a hex value in that case), just use the fade() function. So...

LESS

@color: #ff0000;

.test {
  box-shadow: 2px 2px 5px fade(@color, 99%); 
}

CSS Output

.test {
  box-shadow: 2px 2px 5px rgba(255, 0, 0, 0.99);
}

Upvotes: 11

Related Questions