Functions: Built-in Functions
SASS Built-in Functions
SASS provides a comprehensive library of built-in functions that help you manipulate values and generate CSS more efficiently. These functions are organized into modules covering colors, strings, numbers, lists, maps, and more. Understanding these built-in functions is essential for writing powerful and dynamic stylesheets.
Overview of SASS Built-in Function Modules
SASS built-in functions are organized into several categories:
- Color Functions: Manipulate colors (lighten, darken, saturate, etc.)
- String Functions: Work with text strings
- Number Functions: Perform mathematical operations
- List Functions: Manipulate lists of values
- Map Functions: Work with key-value pairs
- Selector Functions: Manipulate selectors
- Introspection Functions: Inspect values and types
Color Functions
Color functions are among the most useful SASS functions. They allow you to create color variations, theme systems, and dynamic color palettes without manually calculating color values.
lighten() and darken()
These functions adjust the lightness of a color by a percentage.
Lightening and Darkening Colors
$primary-color: #3498db;
.light-button {
background-color: lighten($primary-color, 10%);
// Result: #5DADE2 (lighter blue)
}
.lighter-button {
background-color: lighten($primary-color, 20%);
// Result: #85C1E9 (even lighter)
}
.dark-button {
background-color: darken($primary-color, 10%);
// Result: #217DBB (darker blue)
}
.darker-button {
background-color: darken($primary-color, 20%);
// Result: #1A5490 (even darker)
}
// Practical use: hover states
.button {
background-color: $primary-color;
&:hover {
background-color: darken($primary-color, 5%);
}
&:active {
background-color: darken($primary-color, 10%);
}
}
saturate() and desaturate()
These functions adjust the saturation (color intensity) of a color.
Saturation Manipulation
$base-color: #7fb3d5;
.vibrant {
color: saturate($base-color, 30%);
// More intense, vivid color
}
.muted {
color: desaturate($base-color, 30%);
// More gray, subdued color
}
// Create a muted color palette
$brand-blue: #2980b9;
.header {
background: $brand-blue;
}
.sidebar {
background: desaturate($brand-blue, 20%);
// Creates a more subtle, professional look
}
.footer {
background: desaturate($brand-blue, 40%);
// Even more muted for background elements
}
adjust-hue()
This function rotates the hue of a color around the color wheel by a specified number of degrees.
Hue Rotation
$base-color: #ff0000; // Red
.complementary {
color: adjust-hue($base-color, 180deg);
// Result: #00FFFF (cyan - opposite on color wheel)
}
.analogous-1 {
color: adjust-hue($base-color, 30deg);
// Result: #FF8000 (red-orange)
}
.analogous-2 {
color: adjust-hue($base-color, -30deg);
// Result: #FF0080 (red-pink)
}
// Create a triadic color scheme
$primary: #e74c3c; // Red
.primary {
background: $primary;
}
.secondary {
background: adjust-hue($primary, 120deg);
// Green
}
.tertiary {
background: adjust-hue($primary, 240deg);
// Blue
}
mix()
The mix() function blends two colors together. You can specify the weight (percentage) of the first color.
Color Mixing
$color1: #ff0000; // Red
$color2: #0000ff; // Blue
.mixed-equal {
background: mix($color1, $color2);
// Result: #800080 (purple - 50/50 mix)
}
.mixed-more-red {
background: mix($color1, $color2, 75%);
// Result: #BF0040 (75% red, 25% blue)
}
.mixed-more-blue {
background: mix($color1, $color2, 25%);
// Result: #4000BF (25% red, 75% blue)
}
// Practical use: creating tints and shades
$brand-color: #3498db;
.tint-light {
background: mix(white, $brand-color, 80%);
// Very light tint
}
.tint-medium {
background: mix(white, $brand-color, 50%);
// Medium tint
}
.shade-dark {
background: mix(black, $brand-color, 50%);
// Dark shade
}
rgba(), complement(), invert()
Other Useful Color Functions
$brand-color: #3498db;
// rgba() - Add transparency to any color
.overlay {
background: rgba($brand-color, 0.8);
// 80% opacity
}
.subtle-overlay {
background: rgba($brand-color, 0.2);
// 20% opacity
}
// complement() - Get the complement (opposite) color
.accent {
color: complement($brand-color);
// Returns the color directly opposite on the color wheel
}
// invert() - Invert all color channels
$dark-bg: #2c3e50;
.inverted-theme {
background: invert($dark-bg);
// Creates a light background by inverting
}
// Combine functions for powerful effects
.gradient-button {
background: linear-gradient(
to bottom,
lighten($brand-color, 5%),
darken($brand-color, 5%)
);
&:hover {
background: linear-gradient(
to bottom,
lighten($brand-color, 10%),
$brand-color
);
}
}
String Functions
String functions allow you to manipulate text values, which is useful for generating class names, working with font families, and processing string-based data.
Common String Functions
// quote() and unquote()
$font-name: Arial;
.with-quotes {
font-family: quote($font-name);
// Result: font-family: "Arial";
}
$quoted-font: "Helvetica Neue";
.without-quotes {
font-family: unquote($quoted-font);
// Result: font-family: Helvetica Neue;
}
// str-length() - Get string length
$text: "Hello World";
.debug {
// Length: 11 characters
content: str-length($text);
}
// to-upper-case() and to-lower-case()
$brand: "Acme Corp";
.uppercase {
content: to-upper-case($brand);
// Result: "ACME CORP"
}
.lowercase {
content: to-lower-case($brand);
// Result: "acme corp"
}
// str-insert() - Insert a string at a specific position
$base: "Hello";
.inserted {
content: str-insert($base, " World", 6);
// Result: "Hello World"
}
// str-index() - Find position of substring
$text: "Hello World";
.index {
// Returns: 7 (position of "World")
content: str-index($text, "World");
}
// Practical example: generating utility classes
$sizes: small, medium, large;
@each $size in $sizes {
.btn-#{$size} {
$uppercase-size: to-upper-case($size);
padding: if($size == small, 8px, if($size == medium, 12px, 16px));
&::before {
content: "#{$uppercase-size} BUTTON";
}
}
}
Number Functions
Number functions perform mathematical operations and conversions on numeric values.
Mathematical Number Functions
// percentage() - Convert a unitless number to percentage
.width-half {
width: percentage(0.5);
// Result: 50%
}
.width-third {
width: percentage(1/3);
// Result: 33.33333%
}
// round(), ceil(), floor()
$value: 12.7px;
.rounded {
width: round($value);
// Result: 13px
}
.ceiling {
width: ceil($value);
// Result: 13px (always rounds up)
}
.floor {
width: floor($value);
// Result: 12px (always rounds down)
}
// abs() - Absolute value
$negative: -15px;
.absolute {
margin: abs($negative);
// Result: 15px
}
// min() and max()
.responsive-width {
width: min(100%, 600px);
// Takes the smaller value
}
.responsive-padding {
padding: max(20px, 2vw);
// Takes the larger value
}
// random() - Generate random number
.random-color {
// Generate random RGB values
color: rgb(
random(255),
random(255),
random(255)
);
}
.random-position {
left: percentage(random(100) / 100);
// Random percentage from 0% to 100%
}
// Practical example: Responsive typography with math
$base-font-size: 16px;
$scale-ratio: 1.25;
h1 {
font-size: $base-font-size * $scale-ratio * $scale-ratio * $scale-ratio;
// Result: 31.25px
}
h2 {
font-size: round($base-font-size * $scale-ratio * $scale-ratio);
// Result: 25px (rounded)
}
h3 {
font-size: $base-font-size * $scale-ratio;
// Result: 20px
}
List Functions
Lists in SASS are collections of values separated by commas or spaces. List functions allow you to manipulate and query these collections.
Working with Lists
$colors: red, green, blue, yellow;
$spacing: 10px 20px 30px 40px;
// length() - Get number of items
.total-colors {
content: length($colors);
// Result: 4
}
// nth() - Get item at specific position (1-indexed)
.first-color {
color: nth($colors, 1);
// Result: red
}
.last-color {
color: nth($colors, length($colors));
// Result: yellow
}
// append() - Add item to end of list
$extended-colors: append($colors, purple);
// Result: red, green, blue, yellow, purple
.new-length {
content: length($extended-colors);
// Result: 5
}
// join() - Combine two lists
$primary-colors: red, blue, yellow;
$secondary-colors: green, orange, purple;
$all-colors: join($primary-colors, $secondary-colors);
// Result: red, blue, yellow, green, orange, purple
// index() - Find position of item in list
$sizes: small, medium, large, x-large;
.position {
content: index($sizes, large);
// Result: 3
}
// zip() - Combine multiple lists into nested lists
$names: primary, secondary, accent;
$colors: #007bff, #6c757d, #ffc107;
$theme: zip($names, $colors);
// Result: (primary #007bff), (secondary #6c757d), (accent #ffc107)
// Practical example: Generate spacing utilities
$spacings: 0, 4, 8, 12, 16, 20, 24, 32, 40, 48;
@each $space in $spacings {
.m-#{$space} {
margin: #{$space}px;
}
.p-#{$space} {
padding: #{$space}px;
}
}
// Result: .m-0, .m-4, .m-8, .p-0, .p-4, .p-8, etc.
Advanced List Usage
Complex List Manipulation
// Creating a responsive breakpoint system
$breakpoints: (
xs: 0,
sm: 576px,
md: 768px,
lg: 992px,
xl: 1200px,
xxl: 1400px
);
// Loop through breakpoints (this uses map functions)
@each $name, $value in $breakpoints {
@if $value > 0 {
@media (min-width: $value) {
.container-#{$name} {
max-width: $value - 20px;
}
}
}
}
// Multi-value list processing
$font-stack: (
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
Roboto,
"Helvetica Neue",
Arial,
sans-serif
);
body {
font-family: $font-stack;
}
// Check if value exists in list
$supported-positions: top, right, bottom, left;
@mixin position-check($pos) {
@if index($supported-positions, $pos) {
position: absolute;
#{$pos}: 0;
} @else {
@error "Position #{$pos} is not supported. Use: #{$supported-positions}";
}
}
.top-element {
@include position-check(top);
}
Map Functions
Maps are key-value pairs in SASS, similar to objects in JavaScript or dictionaries in Python. Map functions allow you to work with these data structures efficiently.
Essential Map Functions
// Define a color theme map
$theme-colors: (
primary: #007bff,
secondary: #6c757d,
success: #28a745,
danger: #dc3545,
warning: #ffc107,
info: #17a2b8,
light: #f8f9fa,
dark: #343a40
);
// map-get() - Get value by key
.primary-button {
background-color: map-get($theme-colors, primary);
// Result: #007bff
}
.danger-alert {
border-color: map-get($theme-colors, danger);
// Result: #dc3545
}
// map-has-key() - Check if key exists
@function get-theme-color($key) {
@if map-has-key($theme-colors, $key) {
@return map-get($theme-colors, $key);
} @else {
@warn "Color #{$key} not found in theme!";
@return #000;
}
}
.custom {
color: get-theme-color(primary);
// Works: returns #007bff
}
// map-keys() - Get all keys
$all-theme-names: map-keys($theme-colors);
// Result: primary, secondary, success, danger, warning, info, light, dark
// map-values() - Get all values
$all-theme-colors: map-values($theme-colors);
// Result: #007bff, #6c757d, #28a745, ...
// map-merge() - Combine two maps
$additional-colors: (
purple: #6f42c1,
pink: #e83e8c,
orange: #fd7e14
);
$extended-theme: map-merge($theme-colors, $additional-colors);
// map-remove() - Remove key from map
$no-danger: map-remove($theme-colors, danger, warning);
// Result: map without danger and warning keys
Practical Map Usage
Building a Complete Theme System
// Comprehensive theme configuration
$theme: (
colors: (
primary: #007bff,
secondary: #6c757d,
success: #28a745,
danger: #dc3545
),
spacing: (
xs: 4px,
sm: 8px,
md: 16px,
lg: 24px,
xl: 32px
),
typography: (
base-size: 16px,
line-height: 1.5,
font-family: ('Inter', sans-serif)
),
borders: (
radius: 4px,
width: 1px,
style: solid
)
);
// Helper function to get nested map values
@function theme-get($keys...) {
$value: $theme;
@each $key in $keys {
@if type-of($value) == "map" {
$value: map-get($value, $key);
} @else {
@warn "Key #{$key} not found in theme structure";
@return null;
}
}
@return $value;
}
// Usage of nested theme values
.card {
padding: theme-get(spacing, md);
border-radius: theme-get(borders, radius);
border: theme-get(borders, width) theme-get(borders, style) #ccc;
}
.primary-button {
background: theme-get(colors, primary);
padding: theme-get(spacing, sm) theme-get(spacing, md);
}
// Generate utility classes from map
@each $name, $color in map-get($theme, colors) {
.bg-#{$name} {
background-color: $color;
}
.text-#{$name} {
color: $color;
}
.border-#{$name} {
border-color: $color;
}
}
// Result: .bg-primary, .text-primary, .border-primary, etc.
// Generate spacing utilities
@each $size, $value in map-get($theme, spacing) {
.m-#{$size} {
margin: $value;
}
.p-#{$size} {
padding: $value;
}
.gap-#{$size} {
gap: $value;
}
}
// Result: .m-xs, .m-sm, .p-xs, .p-sm, .gap-xs, etc.
Combining Functions for Powerful Effects
Real-World Example: Dynamic Button Generator
$button-colors: (
primary: #007bff,
success: #28a745,
danger: #dc3545,
warning: #ffc107
);
@mixin generate-button($color-name, $base-color) {
.btn-#{$color-name} {
background-color: $base-color;
border-color: darken($base-color, 5%);
color: if(lightness($base-color) > 50%, #000, #fff);
&:hover {
background-color: darken($base-color, 7.5%);
border-color: darken($base-color, 10%);
}
&:active {
background-color: darken($base-color, 10%);
border-color: darken($base-color, 12.5%);
}
&:disabled {
background-color: desaturate($base-color, 40%);
opacity: 0.65;
}
// Generate outline variant
&-outline {
background-color: transparent;
border-color: $base-color;
color: $base-color;
&:hover {
background-color: $base-color;
color: if(lightness($base-color) > 50%, #000, #fff);
}
}
// Generate light variant
&-light {
background-color: mix(white, $base-color, 85%);
border-color: mix(white, $base-color, 70%);
color: darken($base-color, 10%);
&:hover {
background-color: mix(white, $base-color, 75%);
}
}
}
}
// Generate all button variants
@each $name, $color in $button-colors {
@include generate-button($name, $color);
}
// Results in:
// .btn-primary, .btn-primary:hover, .btn-primary-outline, .btn-primary-light
// .btn-success, .btn-success:hover, .btn-success-outline, .btn-success-light
// ... and so on for all colors
Exercise 1: Color Palette Generator
Create a color palette generator using SASS color functions:
- Start with a base color variable
- Use lighten() to create 5 lighter tints (10%, 20%, 30%, 40%, 50%)
- Use darken() to create 5 darker shades (10%, 20%, 30%, 40%, 50%)
- Generate CSS classes .tint-1 through .tint-5 and .shade-1 through .shade-5
- Add a complementary color using complement() and create its tints and shades
Exercise 2: Spacing System Builder
Build a comprehensive spacing utility system using list and number functions:
- Create a base spacing unit (e.g., 8px)
- Create a list of multipliers: 0, 0.5, 1, 1.5, 2, 2.5, 3, 4, 5, 6, 8
- Use list functions to generate margin and padding utilities for all sides (top, right, bottom, left, x-axis, y-axis, all)
- Use the percentage() function to create width utilities (25%, 50%, 75%, 100%)
- Use round() to ensure all generated values are whole pixels
Exercise 3: Theme Configuration System
Create a theme system using map functions:
- Create a nested map with theme configuration including colors, typography, and spacing
- Write a custom function to safely retrieve nested map values
- Use map-keys() and @each to generate utility classes for all theme colors
- Create a mixin that accepts a color name and generates a complete component style using map-get()
- Add error handling with @warn for invalid color names