CSS Math Functions

CSS Math Functions allow you to perform mathematical operations directly in your CSS. This includes basic arithmetic operations like addition, subtraction, multiplication, and division. These functions help in creating responsive and flexible layouts without relying on external preprocessing tools.

Available Math Functions

The main CSS math functions are:

  • calc(): Performs calculations to determine CSS property values.
  • min(): Returns the smallest value from a list of comma-separated values.
  • max(): Returns the largest value from a list of comma-separated values.
  • clamp(): Clamps a value between an upper and lower bound.

1. calc()

The calc() function allows you to perform calculations to determine CSS property values. It can be used with any valid CSS property that accepts a length, such as width and padding.


/* Using calc() */
.container {
    width: calc(100% - 2rem); /* Subtract 2rem from 100% of the container's width */
}

        
This container width is calculated using calc().

2. min()

The min() function returns the smallest value from a list of comma-separated values. This is useful for setting responsive sizes.


/* Using min() */
.box {
    width: min(80%, 400px); /* Width will be the smaller of 80% or 400px */
}

        
This box width is determined using min().

3. max()

The max() function returns the largest value from a list of comma-separated values. It's useful for ensuring a property value does not fall below a certain threshold.


/* Using max() */
.element {
    font-size: max(16px, 2vw); /* Font size will be the larger of 16px or 2vw */
}

        
This text size is determined using max().

4. clamp()

The clamp() function clamps a value between an upper and lower bound. It allows for fluid resizing within a specified range.


/* Using clamp() */
.text {
    font-size: clamp(1rem, 2vw, 2rem); /* Font size will be between 1rem and 2rem */
}

        
This text size is controlled using clamp().