Sass calculate percent minus px

Sass

Sass Problem Overview


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 '%'.

Sass Solutions


Solution 1 - Sass

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});
}

Solution 2 - Sass

There is a calc function in both SCSS [compile-time] and CSS [run-time]. You're likely invoking the former instead of the latter.

For obvious reasons mixing units won't work compile-time, but will at run-time.

You can force the latter by using unquote, a SCSS function.

.selector { height: unquote("-webkit-calc(100% - 40px)"); }

Solution 3 - Sass

$var:25%;
$foo:5px;
.selector {
    height:unquote("calc( #{$var} - #{$foo} )");
}

Solution 4 - Sass

IF you know the width of the container, you could do like this:

#container
  width: #{200}px
  #element
    width: #{(0.25 * 200) - 5}px

I'm aware that in many cases #container could have a relative width. Then this wouldn't work.

Solution 5 - Sass

Sorry for reviving old thread - Compass' stretch with an :after pseudo-selector might suit your purpose - eg. if you want a div to fill width from left to (50% + 10px) of screen you could use (in SASS indented syntax):

.example
	background: red
	+stretch(0, -10px, 0, 0)
	&:after
		+stretch(0, 0, 0, 50%)
		content: ' '
		background: blue

The :after element fills 50% to the right of .example (leaving 50% available for .example's width), then .example is stretched to that width plus 10px.

Solution 6 - Sass

Just add the percentage value into a variable and use #{$variable} for example

$twentyFivePercent:25%;
.selector {
    height: calc(#{$twentyFivePercent} - 5px);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike FieldenView Question on Stackoverflow
Solution 1 - SasschrisgonzalezView Answer on Stackoverflow
Solution 2 - SasssandstromView Answer on Stackoverflow
Solution 3 - SassEdwin Fernando Marroquin BustoView Answer on Stackoverflow
Solution 4 - SassDesign by AdrianView Answer on Stackoverflow
Solution 5 - SassBryce GilhomeView Answer on Stackoverflow
Solution 6 - SassAftab AhmedView Answer on Stackoverflow