CSS Math Functions

CSS math functions like calc() allow dynamic values. Create flexible and responsive layouts.

On this page

CSS Math Functions

CSS math functions allow you to perform calculations directly in CSS. They are commonly used to create flexible, responsive layouts without JavaScript.

The most commonly used math functions are calc(), min(), max(), and clamp().

calc()

The calc() function lets you combine different units such as percentages, pixels, and rem values.

.container {
  width: calc(100% - 40px);
}

This subtracts 40px from the full width of the parent.

Common use cases:

  • Flexible widths with fixed padding
  • Positioning elements with mixed units
  • Dynamic spacing
.sidebar {
  height: calc(100vh - 64px);
}

min()

The min() function picks the smallest value from a list.

.card {
  width: min(90%, 520px);
}

This keeps the card responsive but prevents it from becoming wider than 520px.

max()

The max() function picks the largest value from a list.

.title {
  font-size: max(1.2rem, 18px);
}

This ensures text never becomes too small.

clamp()

The clamp() function sets a value between a minimum and maximum, with a preferred value in the middle.

h1 {
  font-size: clamp(1.5rem, 4vw, 3rem);
}

This means:

  • Minimum size: 1.5rem
  • Preferred scaling: 4vw
  • Maximum size: 3rem

clamp() is perfect for responsive typography.

Math Functions with Layout

Math functions work well with padding, margins, and grid layouts.

.section {
  padding: clamp(16px, 5vw, 48px);
}

Code Challenge

Goal: Create a responsive card using CSS math functions.

HTML:

<div class="card">
  <h3>Math Functions</h3>
  <p>This card scales smoothly on different screen sizes.</p>
</div>

Task:

  • Limit the card width using min()
  • Use clamp() for padding
  • Use clamp() for responsive font size

Try a Solution:

.card {
  width: min(90%, 520px);
  margin: 40px auto;
  padding: clamp(16px, 4vw, 40px);
  border: 1px solid #ddd;
  border-radius: 12px;
}

.card h3 {
  font-size: clamp(1.2rem, 3vw, 1.8rem);
  margin-top: 0;
}

.card p {
  font-size: 1rem;
  line-height: 1.7;
}

What’s Next?

Next, you will learn techniques for optimizing CSS for performance and maintainability.

CSS Math Functions Examples (9)