Sass calculate percent minus px

Mike Fielden picture Mike Fielden · Nov 7, 2012 · Viewed 131.8k times · Source

I want to be able to do the following:

height: 25% - 5px;

Obviously when I do that I get the error:

Incompatible units: 'px' and '%'.

Answer

chrisgonzalez picture chrisgonzalez · Nov 7, 2012

Sass cannot perform arithmetic on values that cannot be converted from one unit to the next. Sass has no way of knowing exactly how wide "100%" is in terms of pixels or any other unit. That's something only the browser knows.

You need to use calc() instead. Check browser compatibility on Can I use...

.foo {
    height: calc(25% - 5px);
}

If your values are in variables, you may need to use interpolation turn them into strings (otherwise Sass just tries to perform arithmetic):

$a: 25%;
$b: 5px;

.foo {
  width: calc(#{$a} - #{$b});
}