CSS Math Functions

Home / CSS / CSS Math Functions

CSS Math Functions


CSS-Math-Function:

CSS has a few mathematical functions that can be used to perform calculations on property values. These functions are handy for responsive design and for applying dynamic styles to elements based on various factors. Here are some of the key CSS math functions:

calc() Function:

The calc() function allows you to perform arithmetic calculations on property values. It's particularly useful for creating responsive layouts.

Example:


<style>
    p {
      width: calc(50% - 20px);
    }
  </style>

In this example, the width is set to 50% of the container width minus 20 pixels.

min() and max() Functions:

These functions are used to set a property to the minimum or maximum value from a list of comma-separated values. They can be helpful for ensuring that a property doesn't exceed certain limits.

Example:

 
<style>
    p {
      width: min(200px, 50%);
    }
  </style>

In this example, the width is set to the minimum value between 200 pixels and 50% of the container width.

clamp() Function:

The clamp() function is a combination of min(), max(), and a preferred value. It allows you to set a property to a value that falls within a specified range, with a preferred value that's used when it's within that range.

Example:


<style>
    p {
      width: clamp(200px, 50%, 80%);
    }
  </style>

In this example, the width is set to 50% of the container width but will not go below 200 pixels or above 80% of the container width.

round() Function:

The round() function is used to round a numerical value to the nearest whole number.

Example:

<style>
    p {
      font-size: round(1.6em);
    }
  </style>

In this example, the font-size is set to the nearest whole number value of 2em.

abs() Function:

The abs() function is used to return the absolute value of a numerical value. It can be useful for ensuring that a property is always positive.

Example:

<style>
    p {
      margin-left: abs(-20px);
    }
  </style>

In this example, the margin-left is set to 20 pixels, regardless of the sign of the input value.

Math Operators:

CSS also supports standard mathematical operators (+, -, *, /) for performing calculations in property values.

Example:

<style>
    p {
      height: calc(100% - 2 * 20px);
    }
  </style>