# CSS Math Functions

CSS provides mathematical functions `min()`, `max()`, and `clamp()` that allow property values to be calculated dynamically based on a set of values or a range. These are powerful tools for responsive design.

## 1. `min()`

The `min()` function takes one or more comma-separated values and returns the smallest (most negative) value.

**Syntax:** `property: min(value1, value2, ...);`

```css
/* The width will be 50% of the parent, but never more than 300px */
.box {
  width: min(50%, 300px);
}
```
If the parent is 1000px wide, 50% is 500px. `min(500px, 300px)` is 300px.
If the parent is 400px wide, 50% is 200px. `min(200px, 300px)` is 200px.

## 2. `max()`

The `max()` function takes one or more comma-separated values and returns the largest (most positive) value.

**Syntax:** `property: max(value1, value2, ...);`

```css
/* The width will be 50% of the parent, but never less than 300px */
.box {
  width: max(50%, 300px);
}
```

## 3. `clamp()`

The `clamp()` function clamps a value between an upper and lower bound. It takes three parameters: a minimum value, a preferred value, and a maximum value.

**Syntax:** `property: clamp(MIN, VAL, MAX);`

It is equivalent to `max(MIN, min(VAL, MAX))`.

```css
/* Font size is 2.5vw (responsive), but won't go below 1rem or above 2rem */
h1 {
  font-size: clamp(1rem, 2.5vw, 2rem);
}
```

## 4. Use Cases

### Fluid Typography
Using `clamp()` for font sizes ensures text scales with the viewport but remains readable on small screens and doesn't get ridiculously huge on large screens.

### Responsive Containers
Using `min()` for widths allows elements to be fluid (`%` or `vw`) but capped at a maximum width (`px` or `rem`), replacing the need for `width: 100%; max-width: 600px;`.

```css
.container {
  width: min(100% - 2rem, 600px);
  margin-inline: auto;
}
```

[[programming/css/css]]
[[programming/css/calc-function]]
[[programming/css/units]]