Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sass interpolate a variable name to string

We were provided a number of colors with specific hover-state colors associated:

$red: #cb333b;
$red-hover: #fe666e;
$brown: #544742;
$brown-hover: #877a75;
etc.

Since all the colors are formatted the same way, so I was hoping to write a mixin that takes the color's variable name, then concatenates -hover to the end. This is my first try:

@mixin button_colorizor($color) {
  border-color: $color;
  color: $color;
  &:hover {
    color: #{$color}-hover;
    border-color: #{$color}-hover;
  }
}

But what this does is output a color like this: #f1735f-hover. The same thing when I do this: color: #{$color+-hover};

like image 829
icicleking Avatar asked Aug 15 '16 20:08

icicleking


People also ask

How do you use interpolation in Sass?

Interpolation is a new principle and it is widely used in SASS. To interpolate an expression we need to wrap the expression using #{ }. where ….. represents some text. Interpolation in SASS expressions always returns an unquoted string, no matter whether the string is quoted or not.

How do you interpolate a variable?

Use a template literal to interpolate a variable in a string, e.g hello ${myVar} . Template literals are delimited with backticks and allow us to embed variables and expressions using the dollar sign and curly braces ${expression} syntax.

What is #{} in SCSS?

is the css class selector, #{} interpolation syntax it allows the using of the variables in selectors and property names $name: foo; $attr: border; p. #{$name} { #{$attr}-color: blue; }

Which strings do interpolate variables?

String interpolation is common in many programming languages which make heavy use of string representations of data, such as Apache Groovy, Julia, Kotlin, Perl, PHP, Python, Ruby, Scala, Swift, Tcl and most Unix shells.


1 Answers

You can create map of colors. And get color values by its names.

Demo on sassmeister.

$colors: (
  red: #cb333b,
  red-hover: #fe666e,
  brown: #544742,
  brown-hover: #877a75
);

@mixin button_colorizor($color) {
  color: map-get($colors, $color);
  border-color: map-get($colors, $color);

  &:hover {
    color: map-get($colors, $color + '-hover');
    border-color: map-get($colors, $color + '-hover');
  }
}

a {
  @include button_colorizor(red);
}

span {
  @include button_colorizor(brown);
}

This code is compiled to css:

a {
  color: #cb333b;
  border-color: #cb333b;
}
a:hover {
  color: #fe666e;
  border-color: #fe666e;
}

span {
  color: #544742;
  border-color: #544742;
}
span:hover {
  color: #877a75;
  border-color: #877a75;
}
like image 62
3rdthemagical Avatar answered Oct 15 '22 21:10

3rdthemagical