Skip to main content

Introduction to Sass Numeric Functions

Sass Numeric Functions

Here are some Sass numeric functions that you can use to manipulate numbers in your stylesheets:

  • percentage() - Converts a unitless number to a percentage.
$width: 0.5;
width: percentage($width);
// output: width: 50%;

  • round() - Rounds a number to the nearest integer.
$number: 3.7;
number: round($number);
// output: number: 4;

  • ceil() - Rounds a number up to the nearest integer.
$number: 3.1;
number: ceil($number);
// output: number: 4;

  • floor() - Rounds a number down to the nearest integer.
$number: 3.9;
number: floor($number);
// output: number: 3;

  • abs() - Returns the absolute value of a number.
$number: -3.7;
number: abs($number);
// output: number: 3.7;

  • min() - Returns the minimum value of two or more numbers.
$min-value: min(2, 5, 1, 4);
// output: min-value: 1;

  • max() - Returns the maximum value of two or more numbers.
$max-value: max(2, 5, 1, 4);
// output: max-value: 5;

  • random() - Returns a random number between 0 and 1.
$random-number: random();
// output: random-number: 0.2836281633;

  • sqrt() - Returns the square root of a number.
$number: 25;
number: sqrt($number);
// output: number: 5;

These are some examples of Sass numeric functions that you can use to manipulate numbers in your stylesheets.

How to Use Sass Numeric Functions

To use Sass numeric functions, you need to follow these steps:

  • Define a numeric variable or a numeric value that you want to manipulate.

As an example:

$width: 0.5;
  • Call the desired numeric function with the numeric variable or value as an argument.

As an example:

$percentage: percentage($width);
  • Use the returned value of the numeric function in your stylesheets.

As an example:

.container {
width: $width * 100%;
height: $percentage;
}

In this example:

  • We are using the percentage() function to convert the $width variable from a unitless number to a percentage.
  • We are then using the returned value of the function in the height property of a .container class.
  • This will set the height of the .container element to 50% of its width.

You can use any other numeric function in the same way. Just pass the numeric variable or value as an argument to the function and use the returned value in your stylesheets.