21

I need to define a width in my SCSS code as so:

#example {
  width: $currentWidth + 349 !important;
}

Where $currentWidth is defined by the loop.

However, Sass always ends up concatenating the two numbers instead of doing the arithmetic.

I have also tried:

width: #{$currentWidth + 349}px !important;

Which still results in concatenation.

I'm wondering what I'm doing wrong? I know this is incredibly basic, but I also can't seem to find good information on how Sass handles arithmetic

khollenbeck
  • 16,028
  • 18
  • 66
  • 101
waffl
  • 5,179
  • 10
  • 73
  • 123
  • 4
    Is `$currentWidth` a string or a number? If it is a string, then it will concatenate. Sass can only do arithmetic if both entities are of the number type (ie. Sass interprets `"10" + 349` the same way it does `"meatloaf" + 349`). – cimmanon Sep 05 '13 at 14:47
  • The most straight forward solution for this particular case could be: `width: $currentWidth + 349px !important` which works like a charm and is very straight forward. – Axel Mar 13 '18 at 14:17

1 Answers1

37

Assuming $currentWidth is an integer.

SASS:

$currentWidth: 30;

#example {
  width: unquote( ($currentWidth + 349) + 'px ' + !important );
}

CSS OUTPUT:

#example {
  width: 379px !important;
}

You can test it here:

http://sass-lang.com/try.html

khollenbeck
  • 16,028
  • 18
  • 66
  • 101
  • By concatenating the unit onto the integer like this, you're getting a string. This is wrong and you should *never* do this *ever*. – cimmanon Mar 04 '15 at 14:51
  • 1
    Exactly what I said: `($currentWidth + 349) + 'px '` is a string. You should **never** do this if you're trying to change a unitless value to a united value. – cimmanon Mar 04 '15 at 18:50
  • Okay I sort of see what you are saying, but you didn't really explain why to "never" do this. Also, what would you recommend? Would this `#example { width: abs($currentWidth + 349) + px !important; }` be a better way? – khollenbeck Mar 04 '15 at 20:20
  • No. You're not getting it. It's still a string. – cimmanon Mar 04 '15 at 22:20
  • 15
    And you still haven't explained why this is an issue. – khollenbeck Mar 06 '15 at 14:51
  • 1
    This syntax is very uncomfortable. I thought it was a best practice to assign integer value to variable instead of pixel value. Isn't it? (`$my-width: 100;` instead of `$my-width: 100px;`) – Augustin Riedinger Mar 30 '15 at 10:45
  • 1
    The most straight forward solution for this particular case could be: `width: $currentWidth + 349px !important` which works like a charm and is very straight forward. – Axel Mar 13 '18 at 14:18