Understand mathematical functions in CSS
CESS

CESS

6 min readMay 13 2022

Understand mathematical functions in CSS

Most developers are not familiar with the mathematical functions of CSS. This function reduces the need for media queries, making it easier to create responsive websites.

We will discuss how to use the mathematical functions of CSS in this article.

Prerequisite

To follow along with this article, we'll need:

  • Basic HTML and CSS knowledge.
  • A code editor to practice along, preferably Visual studio code. To download Visual studio code, click here.

CSS Mathematical Functions

CSS mathematical functions perform different mathematical operations using different CSS values. These functions accept one or more values and return a single value. We use mathematical operators like - and + on the CSS values to get a new value for the CSS property.

Types of CSS Mathematical Functions

There are four math functions well supported by CSS:

  • The Calc() Function
  • The Min() Function
  • The Max() Function
  • The clamp() Function

The Calc() Function

The calc() function lets us calculate CSS property values using mathematical calculations. It accepts a specific expression as an input and returns the expression's output as the value.

This function comes in handy for designing responsive web pages and apps.

The syntax for the calc() function is as follows:

    .class-name {
      property: calc(expression);
    }

The expression combines different CSS values and mathematical operators, such as - and +.

Points to Remember Before Using the Calc() Function.

Before using the calc() function, keep these things in mind:

  1. It is compulsory to use whitespaces around addition and subtraction operators. We can use multiplication and division with or without whitespaces.
    // Invalid
    .class-name {
        property: calc(100% -70px);
    }  // It will read as a percentage followed by a negative length.
    
    // Valid
    .class-name {
      property: calc(100% - 70px);
    } // It will read as a percentage(%) followed by a subtraction operator and a length.
  1. Both numbers must either have units or not have units for addition and subtraction.
    // invalid
    .class-name {
      property: calc(100% - 70);
    }
    // Valid
    .class-name {
      property: calc(100% - 70px);
      font-weight: calc(300 + 400);
    }
  1. The calculation in the calc() function begins on the left and ends on the right. Division and multiplication come first, followed by addition and subtraction. We place a parenthesis() around the parts we want to solve first to override precedence.
  2. When using the calc() method to divide, the right-hand side must be a number without a unit attached to it. For multiplication, the location of the number does not matter. It can be on the left or right.
    // Invalid
    .class-name {
     property: calc(30px / 20px); 
     property: calc(5 / 20px);
     property: calc(300px * 2000px);
    }
    // Valid
    .class-name {
    property: calc(300px / 20);
    property: calc(2 * 300px); 
    property: calc(300px * 2); 
    }
  1. We can also use calc() for only a part of a CSS attribute value or use it without doing a math calculation.
    .class-name {
      margin: 10px calc(200px / 10);
      width: calc(200px); // is the same as width: 200px;
    }

How Does the Calc() Function in CSS Work?

The following examples illustrate how to use calc():

Example 1

Using calc() function with different units.

The calc() function allows us to combine different units, and it's not compulsory to use a specific unit.

HTML Code:

    <div class="container">
      exercise
    </div>

CSS Code:

    .container {
        text-align: center;
        background-color: crimson;
        color: white;
        font-size: 1.7em;
        font-weight: 700;
        padding: 3em;
        width: calc(100% - 100px);
    }

Our output will be:

We'll see a 100px space by the right side of our browser. calc(100% - 100px) will fill the entire width of 100% except for 100px.

What happens if we shift the above container to the middle?

When we shift the above container to the middle, the 100px will divide in half, giving each side 50px. We will have a margin of 50px on the left and right. Add margin: 2em auto; to the above CSS code when practicing.

If we resize the browser, we will find that the container is responsive across all sizes. That's the beauty of using the calc() function. It is easier to create responsive layouts.

Example 2:

Nesting calc() function.

This function allows us to nest calc() functions. To nest calc() means to place one calc() inside of another.

     .container {
    // Instead of doing this
     height: calc(1000px - calc(200px + 400px));
    // Do this
     height: calc(1000px - (200px + 400px)); // The parent calc() can function on its own.
    } // Output will be 400px

Example 3

Using calc() function with CSS variables

One of calc()'s most convenient features is its ability to work with CSS variables.

    // Local scope
    .container {
    --width: 100px;
    width: calc(var(--width) * 4); // The output will be 400px
    }

The Min() Function

The min() function lets us set the smallest acceptable value. It selects the smallest value from two or more values separated by a comma as the CSS property value.

The syntax for the min() function is as follows:

    .class-name {
      property: min(value1, value2...); 
    }

Points to Remember Before Using the Min() Function.

  1. We can do math inside the min() function without using the calc() method. Maths in min() follow the same rules as maths in calc().

    .class-name {
       property: min(70px - 15px, 30px);
    }
  1. The order in which the min() values appear has no bearing on the choice of the minimum value.

    .class-name {
       property: min(60%, 700px);
      // It is the same as:
      property: min(700px, 60%);
    }

How Does the Min() Function in CSS Work?

The following examples illustrate how to use min():

Example 4

Using min() function with the width property.

HTML Code:

    <div class="container">
      CODE
    </div>

CSS Code:

    .container { 
    background-color: crimson; 
    height: 200px; 
    width: min(60vw, 700px); 
    margin: 2em auto; 
    text-align: center; 
    padding: 2em; 
    font-size: 2rem; 
    color: white;
    }

Our output will be:

For example, 4:

  • When we resize our browser, it checks the screen size and selects the smallest value from the list of values.
  • For example, on a large screen with a resolution of 1200px, it chooses 700px because it is the lower of the two values.
  • In cases when the screen size is less than 700px, it selects 60vw of the current screen size
  • When the screen size is bigger than 700px or reaches 700px, it falls back to 700px. It never exceeds 700px

Example of how to calculate the viewport size for a 1200px screen resolution:

  • Using the VW format, 1vw equals 1% of the viewport (screen) size, not the parent element. So 60vw is 60% of the screen size of 1200px
  • 60vw / 100% * 1200px = 720
  • The 720 result in the above calculation is less than 700px, so the large screen selects 700px

Writing width: min(60vw, 700px); is the same as writing:

    width: 60vw;
    max-width: 700px;

The min() function allows us to write our max-width and width in one parenthesis. It is an easy way to set the maximum value on any element.

Example 5

Using min() function for font-sizes.

    .container {
    font-size: min(7rem, 2vw);
    color: grey;
    }

The font size in the example above will never exceed 7rem and will shrink or reduce to 2vw on smaller screens. Depending on the screen size, the font size will range between 2vw and 7rem.

The Max() Function

By contrast, the max() function does the opposite of the min() function. It selects the largest value from two or more values separated by a comma as the CSS property value.

The syntax for the max() function is as follows:

    .class-name {
      property: max(value1, value2...); // Parameters we pass into the function
    }

NOTE: The points to remember before using the min() also apply to the max() function.

How Does the Max() Function in CSS Work?

The following examples illustrate how to use max()

Example 6

Using max() function with the width property.

Replace the width in example 4 with width: max(60%, 700px);. We will notice that:

  • Based on the screen size, the max() function chooses the largest value between 60% and 700px. It never goes below 700px, and it's responsive across all screen sizes
  • It selects 60% on a large screen as it is the larger of the two value options

Writing width: max(60%, 700px); is the same as writing:

    width: 60%;
    min-width: 700px;

The max() function allows us to write our min-width and width in one parenthesis. It is an easy way to set the minimum value on any element.

Example 7

Using max() function for font-sizes.

    .container {
    font-size: max(7rem, 2vw);
    color: grey;
    }

The font size in the example above will never go below 2vw. The font size will range between 2vw and 7rem, depending on the screen size. It selects 7rem on large screens and 2vw on smaller screens.

NOTE: For ease of understanding, always remember the min() sets a maximum width, and the max() sets a minimum width.

The clamp() Function

CSS clamp() lets us set a property's value between a minimum and maximum. It's practically a combination of the min() and max() functions.

This function aims to prevent headers with huge fonts from taking up too much screen space. Our font-size values will adjust to fit all screen sizes with this function.

The syntax for the clamp() function is as follows:

    .class-name {
     property: clamp(minValue, preferredValue, maxValue);
    }

This function only accepts three parameters, all of which must be in the correct order.

  • The minValue: The first value in the parentheses should always be the minimum value. It's the smallest value. The selection of the minValue occurs if the preferredValue is less than the minValue.
  • The preferredValue: The preferred value is also called the default or ideal value. Preferred values are automatically selected if the value is between the min and max value. Suppose the default value is larger than the min value but less than the max value
  • The maxValue: The last value in the parenthesis should always be the maximum value. It's the largest value. The selection of the maxValue will occur if the preferredValue is greater than the maxValue

How does the clamp() function in CSS work?

The following examples illustrate how to use clamp():

Example 8

Using clamp() function with the width property.

    .container {
    background-color: grey;
    width: clamp(250px, 40vw, 800px); 
    }

On a big screen resolution of 1400px:

  • The 40vw of our 1400px screen resolution is 560px
  • The minimum width is 250px
  • The preferred or default value is 40vw. If the width is larger than 250px but less than 800px, the browser will use the preferred value of 40vw. So the width of the big screen will be 560px
  • The maximum width is 800px. The width will not exceed 800px. Depending on the screen resolution, it will range between 250px, 40% and 800px

Example 9

Using clamp() function for font-sizes.

    .container {
    font-size: clamp(2rem, 2.5vw, 5rem);
    color: grey;
    }

For example, 9:

  • The minimum font size is 2rem while the maximum font size is 5rem
  • The preferred font size is 2.5vw. The font size will grow with the size of the screen. It will never go below 2rem or exceed 5rem

Check out this online calculator for font size calculation with CSS clamp(). Enter the min and max font sizes, and the calculator will recommend a preferred font size.

Note: We can use any of the math functions for any CSS properties as long as they can accept a numerical value. Thus, CSS properties such as colors, padding, margins, etc., will work with this function.

Conclusion

This article has taught us how to use the different types of CSS math functions. We will be able to create faster and better responsive websites by using CSS math functions.

Resources

Here are some resources that may be useful:


About the author

Web Developer & Technical Writer

More articles

logo
Get insights and tips on technical Content creation

Augment your marketing and product team to publish original technical content written by subject-matter experts for developers.

+1 (302) 703 7275

hi@hackmamba.io

Copyright © 2024 Hackmamba. All rights reserved