Doing math on variable argument Sass mixins

Doug Hamlin picture Doug Hamlin · Oct 17, 2013 · Viewed 38.5k times · Source

I like to use rem units with pixel fallbacks for my CSS sizing and am trying to make mixins to help with that. For font-size, this is easy:

@mixin font-size($size) {
  font-size: $size + px;
  font-size: ($size / 10) + rem;
}

But for padding, margin, etc. the mixin needs to accept variable arguments, which is possible per the Sass documentation http://sass-lang.com/documentation/file.SASS_REFERENCE.html#variable_arguments

However, with the following mixin, instead of dividing by 10, the mixin is just adding a slash between the numbers. That is, this:

@mixin padding($padding...) {
    padding: $padding + px;
    padding: ($padding / 10) + rem;
}
.class {
    @include padding(24);
}

Outputs this:

.class {
    padding: 24px;
    padding: 24/10rem;
}

Instead of this, like I would expect:

.class {
    padding: 24px;
    padding: 2.4rem;
}

Is there a way to make sure Sass recognizes the variables as numbers and thus uses the division operator on them correctly?

Also, after testing this more, I realized the concatenation only takes place on the last variable.

Answer

Owen C. Jones picture Owen C. Jones · Oct 17, 2013

Try this:

padding: #{$padding / 10}rem;

Concatenating in SASS/SCSS uses ruby syntax, and you were mixing a mathematical equation followed by a concatenation, which is a variable type mix, so it's not suprising to me that it didn't work.

Expressions and variables included within #{here} are assesed as if seperate to the rest of the line, and thus don't typecast the rest of the line. Also comes in handy if your output is getting quoted when you didn't expect (as does the unquote() function)