SASS Calc function with examples in CSS|SCSS


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

This tutorial talks about calc function usages examples

calc function in SASS

We already have calc function in CSS which calculates the expression at browser,Where as 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

some times, 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 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 substracting pixel values.

Here calc function is accepting percentage value and pixel value, using minus symbole, It generates css calc function and runs at 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.