0

I'm trying to create a mixin or function that can be passed a property and output that property with separate changed setting.

I have a mixin here called emm:

//Not to change, I use this in multiple scenarios 

$browser-context: 16;
@function emm($pixels, $context: $browser-context) {
  @if (unitless($pixels)) {
    $pixels: $pixels * 1px;
  }
  @if (unitless($context)) {
    $context: $context * 1px;
  }
  @return $pixels / $context * 1em;
}

From this, I can pass in a pixel size and it will output the em for me. Great.

I'm now trying to pass a property through a separate mixin or function that will do this, like so:

@mixin em($style, $pixels) {
  $style: $pixels;
  $style: emm($pixels);
}

div {
  background: red;
  height: emm(20px);

  @include em(font-size, 20px);
}

Hoping for an output like so:

div {
  background: red;
  height: 1.25em;
  font-size: 20px;
  font-size: 1.25em;
}

But it doesn't work, this one is the last thing I've tried and I thought this was , any thoughts?

I'm aware I could make one specifically for font-size, but I'm hoping to use it for multiple properties without making multiple mixins.

Sjrsmile
  • 253
  • 1
  • 5
  • 20

1 Answers1

0

Figured it out! As you might know, SASS outputs are fun, one way to do it is to put a variable inside of #{} to make it work. So here's how I got it to work:

$browser-context: 16;
@function emm($pixels, $context: $browser-context) {
  @if (unitless($pixels)) {
    $pixels: $pixels * 1px;
  }
  @if (unitless($context)) {
    $context: $context * 1px;
  }
  @return $pixels / $context * 1em;
}

@mixin em($style, $pixels) {

  #{$style}: $pixels;
  #{$style}: emm($pixels);
}

div {
  background: red;
  height: emm(20px);

  @include em(font-size, 20px);
}

// OUTPUT

div {
  background: red;
  height: 1.25em;
  font-size: 20px;
  font-size: 1.25em;
}
Sjrsmile
  • 253
  • 1
  • 5
  • 20