Open In App

How to calculate percent minus px in SASS ?

Calculating the difference between percent and px is not as simple as 50% – 30px. Obviously you’ll be getting incompatible unit error. This is because SASS cannot perform arithmetic operations on values that cannot be converted from one unit to another. SASS does not know exactly how wide a “percentage (%)” is in terms of pixels or any other unit. Only the browser is capable of knowing such things.

So here comes the need of calc() function.



About calc(): The calc() function allows us to perform mathematical operations on property values. Instead of declaring, for example, static pixel values for an element’s width, we can use calc() to specify that the width is the result of the addition of two or more numeric values.

Note: The calc() function can be used to perform addition, subtraction, multiplication, and division calculations with numeric property values. Specifically, it can be used with length, frequency, angle, time, number, or integer data types.

example:




.class {
    width: calc(50vmax + 3rem);
    padding: calc(1vw + 1em);
    transform: rotate( calc(1turn + 28deg));
    background: hsl(100, calc(3 * 20%), 40%);
    font-size: calc(50vw / 3);
}

Complied file:

.class {
  width: calc(50vmax + 3rem);
  padding: calc(1vw + 1em);
  transform: rotate(calc(1turn + 28deg));
  background: hsl(100, calc(3 * 20%), 40%);
  font-size: calc(50vw / 3);
}

Article Tags :