Skip to content

Example: clamp Built-in

The clamp function constrains a value between minimum and maximum bounds — a direct mapping to CSS clamp().

Definition

scss
---
module: builtins
title: "Built-in: clamp"
summary: Constrain a value between a minimum and maximum.
category: math
since: 0.1.0
tags: [math, clamp, constraint]
---

/// @name clamp
/// @summary Constrain a value between minimum and maximum bounds.
/// @param $min <number|dimension|ref> The lower bound.
/// @param $preferred <number|dimension|ref> The preferred value.
/// @param $max <number|dimension|ref> The upper bound.
/// @returns <number|dimension>
/// @constraints $min <= $max
/// @example clamp(8px, 12px, 24px) → 12px
/// @example clamp(8px, 4px, 24px) → 8px
/// @example clamp(8px, 32px, 24px) → 24px
@function clamp($min, $preferred, $max) {
  @return clamp($min, $preferred, $max);
}

Usage in Tokens

json
{
  "spacing": {
    "responsive": {
      "$value": "16px",
      "$type": "dimension",
      "$extensions": {
        "org.dtcg-formulas": {
          "formula": "clamp(8px, {spacing.base}, 24px)",
          "definition": "builtins#clamp"
        }
      }
    }
  }
}

Behavior

ExpressionResult
clamp(8px, 12px, 24px)12px (within bounds)
clamp(8px, 4px, 24px)8px (clamped to min)
clamp(8px, 32px, 24px)24px (clamped to max)

Released under the MIT License.