Newcoma
Newcoma

Reputation: 809

Sass function with multiple values

Hello I have this functions that calculates a rem value based on a pixel input and base size

@function unit($number) {
  @return $number / ($number * 0 + 1);
}

@function calcRem($size, $_base-fontsize:16px) {
  $remSize: unit($size) / strip-unit($_base-fontsize);
  @return #{$remSize}rem;
}

.image {
            padding-top:calcRem(250px);
}

I would like to be able to call it with a shorthand like

.image {
            padding:calcRem(250px 25px 10px 50px);
}

How do I do that?

Upvotes: 0

Views: 1987

Answers (2)

Newcoma
Newcoma

Reputation: 809

I made a small variation to make into a function returning pixels converted to rems.

@function unit($number) {
  @return $number / ($number * 0 + 1);
} 

@function paddingRems($paddingPixels, $_base-fontsize:16px) {
    $paddingRems: ();
      @each $padding in $paddingPixels {
        $paddingRems: append($paddingRems, strip-unit($padding) / strip-unit($_base-fontsize) +    rem,'space');  
  }

  @return  $paddingRems;
} 

.image {
        padding:paddingRems(250px 25px 10px 50px);
}

Upvotes: 0

skoller
skoller

Reputation: 89

I'm assuming you're using the strip-unit function featured by Hugo Giraudel on CSS-Tricks in conjunction with the rest of your code.

I found his article on Sass lists to be of great help: http://hugogiraudel.com/2013/07/15/understanding-sass-lists/

Here's how to expand this calculation to use multiple arguments using a mixin:

@function unit($number) {
  @return $number / ($number * 0 + 1);
}

@mixin paddingRems ($paddingPixels: 0 0 0 0, $_base-fontsize:16px) {
  // Create empty SASS variable to hold array of calculated rem values
  $paddingRems: ();

  // Loop over $paddingPixels arguments array
  @each $padding in $paddingPixels {
    // For each argument, perform the calculation, add 'rem' to the end, and remove the quotes.
    // Then, append the argument to the new variable / array, using spaces instead of commas as separators.
    $paddingRems: append($paddingRems, unquote(unit($padding) / strip-unit($_base-fontsize) + 'rem'), 'space');
  }

  // Set the contents of the calculated arguments array to the shorthand version of the padding CSS property.
  padding: $paddingRems;
}

.image {
  @include paddingRems(250px 10px 20px 10px);
}

Also available as a Gist: https://gist.github.com/StephenKoller/31f2e4b4260909fb60b303cd994903d3

Upvotes: 1

Related Questions