Codeskill

Learn to code, step by step

Harnessing Functions and Operators in SASS: Elevating CSS to New Heights

A look at functions and operators in SASS. Tools for doing calculations and manipulating values directly in your stylesheet. Plain CSS has caught up in some areas, but SASS still makes this kind of logic straightforward.

Understanding functions and operators in SASS

Functions and operators let you perform calculations and transform values without leaving your stylesheet. That means fewer hard-coded numbers and stylesheets that adapt when you change a base value.

Arithmetic operations

SASS supports standard operators: +, -, *, and /. You can do maths right in your CSS.

Calculating column widths for a fluid grid:

$container-width: 100%;
$column-gap: 20px;
$number-of-columns: 3;

.column {
  width: ($container-width - ($column-gap * ($number-of-columns - 1))) / $number-of-columns;
}

That adjusts each column width based on the total width, number of columns, and gap between them.

Built-in functions

SASS includes built-in functions for colours and sizes. Functions like lighten(), darken(), and mix() give you control over colour schemes without working out hex values by hand.

A hover effect with a slightly darker button colour:

$button-color: #3498db;

.button {
  background-color: $button-color;
  &:hover {
    background-color: darken($button-color, 10%);
  }
}

The darken() function adjusts the hover colour without hard-coding a separate value.

Custom functions

You can also define your own functions for calculations you use repeatedly:

@function ideal-text-size($viewport, $min-size, $max-size) {
  @return $min-size + ($max-size - $min-size) * ($viewport / 1000);
}

body {
  font-size: ideal-text-size(100vw, 14px, 18px);
}

That adjusts font size based on viewport width for readability across screen sizes.

Best practices for using functions and operators

  1. Use sparingly: Calculations are useful, but too many make a stylesheet hard to read. Apply them where they solve a real problem.
  2. Keep performance in mind: Complex calculations add compile time. Balance flexibility with simplicity.
  3. Document your code: When you write custom functions or non-obvious calculations, a brief comment helps anyone else (or future you) understand the intent.

Functions and operators turn SASS from a convenience layer into something genuinely powerful for dynamic styling. Start with the built-ins and add custom functions when you find yourself repeating the same calculation.

PreviousMastering Mixins in SASS: The Power of Reusable Code