{

SASS Calc function with examples in CSS|SCSS


SASS is a pre-processor for CSS language. It is an advanced CSS for large applications. It provides a calc function to calculate athematic values for different CSS units.

This tutorial talks about calc function usage examples.

calc function in SASS

We already have a calc function in CSS that calculates the expression at the browser, Whereas calc in SASS is compile-time only. calc function accepts numeric values for addition,subtraction,division and percentage. Numeric values are different units like 10px,20%, 1rem etc.

Syntax:

calc(expression)

expression is evaluated to units like px, em, etc…

sitewidth:900px;
 .container {
  width: calc($sitewidth-20px);
  margin-left: 10px;
  margin-right: 10px;
}

Generated CSS would be

.container {
  width: 880px;
  margin-left: 10px;
  margin-right: 10px;
}

How to use sass variable in calc function

Calc function can also contain sass variables used. sass variable can be used in calc with interpolation syntax with spaces.

Interpolation syntax used here #{variablename}

$padding: 10px;

div {
  padding-left: calc(#{$padding} + 10px);
  background: gray;
}

calculate percentage with pixels

sometimes, We need to calculate percentages and addition with static numeric units. This will be generated as CSS calc function and calculates the percentage value at browser only

As sass runs at compile time and is not able to find the percentages of source value.

.header { 
    height: calc(10% + 10px); 
} 

Generated CSS is

.header { 
    height: calc(10% + 10px); 
} 

sass variable percentages minus pixel

sass variables can hold percentage values which can be used in calc function subtracting pixel values.

Here calc function is accepting the percentage value and pixel value, using the minus symbol, It generates the CSS calc function and runs at the browser only.

$pageheight:20%;
.header {
    height: calc(#{$pageheight} - 5px);
}

Compiled css:

.header{
height: calc(#{$pageheight} - 5px);
}
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.