CSS Math Functions

CSS math functions let you compute lengths and other values directly in your stylesheet, which is the foundation of fluid, responsive sizing.

Instead of hard-coding a single number, functions like <code>calc()</code>, <code>min()</code>, <code>max()</code>, and <code>clamp()</code> let the browser work out a value at render time, even mixing units such as percentages and pixels.

calc() For Mixed Units

Full width minus a fixed gutter

<!DOCTYPE html>
<html>
<head>
<style>
.content {
  width: calc(100% - 260px);
}
</style>
</head>
<body>

<div class="content">
  <p>This content area fills the remaining width.</p>
</div>

</body>
</html>

Here the content fills the parent but always leaves 260px for a sidebar. Remember that the plus and minus operators must have a space on each side, or the expression is ignored.

The Four Common Functions

FunctionWhat it returns
calc(a + b)The computed result of an expression
min(a, b, ...)The smallest of the listed values
max(a, b, ...)The largest of the listed values
clamp(min, ideal, max)The ideal value, kept within a range

clamp() For Fluid Type

Font size that scales but stays readable

<!DOCTYPE html>
<html>
<head>
<style>
h1 {
  font-size: clamp(1.5rem, 4vw, 3rem);
}
</style>
</head>
<body>

<h1>Responsive Heading</h1>

</body>
</html>

This heading grows with the viewport width, but never shrinks below 1.5rem and never exceeds 3rem, so it stays legible on both phones and large monitors.

min() And max() In Practice

A container that caps its own width

<!DOCTYPE html>
<html>
<head>
<style>
.wrap {
  width: min(100%, 1100px);
  margin: 0 auto;
}
</style>
</head>
<body>

<div class="wrap">
  <p>This container never grows past 1100px.</p>
</div>

</body>
</html>
Note: You can nest these functions, for example clamp() built from calc() expressions, to express layout rules that would otherwise need several media queries.

Exercise: CSS Math Functions

What is the main benefit of the calc() function in CSS?