Why do Math in CSS? Math functions in CSS can make your life easier. It makes reading the CSS easier. You can save time by avoid having to do the calculations yourself.

Getting Started with CSS

Photo By: Chenspec on Pixabay

Use mathematical expressions to calculate property values such as width or padding.

What type of Math functions can you use?

  • calc()
  • max()
  • min()
  • clamp()

These four Math functions are currently supported by all browsers.

calc()

The calc() function allows you to do basic math. Add, subtract, multiply and divide. You use it the calculate the value for different properties.

This example shows using calc() to calculate a width using subtraction:

.main-content {
  width: calc(100% - 20px);
}

Or you could use it to set the value for part of a property. For example:

.custom-el {
  margin: 10px calc(3em + 2px);
}

You can learn more about how to use this useful function from CSS-Tricks in A Complete Guide to calc().

max()

The max() function takes the largest value from a list of values and sets it to the property value. For example, you may want to set the width to be either 50% or 300px. It picks the value that happens to be larger depending on the viewport size.

.custom-box {
  width: max(50%, 300px);
}

min()

The min() function does the opposite of max(). It takes the smallest value and sets it to the property value. In the custom-box example, you could:

.custom-box {
  width: min(50%, 300px);
}

In this case, the custom-box could not get bigger than 300px.

clamp()

The clamp() function takes three parameters. A minimum value, preferred value and maximum value. It selects a middle value with between the smallest and largest values. clamp() uses that value and sets it to the property.

For example, you can use it for setting a font size that grows with the size of the viewport. Your font won’t get smaller or larger than the specified values. By using clamp(), you can achieve the same effect as the code in Fluid Typography with less code.

Learn more about using Math in CSS