CSS Math Functions - Detailed Overview

Introduction to CSS Math Functions

CSS provides several math functions to dynamically calculate values for various properties. These functions help in creating responsive and adaptable designs.

CSS Math Functions

The following math functions are available in CSS:

Examples of CSS Math Functions

/* Example using calc() */
.example1 {
    width: calc(50% - 20px);
    height: calc(100px + 20px);
    background-color: #FF5722;
}

/* Example using min() and max() */
.example2 {
    width: min(300px, 50%);
    height: max(100px, 10vw);
    background-color: #3F51B5;
}

/* Example using clamp() */
.example3 {
    width: clamp(150px, 30%, 300px);
    height: clamp(100px, 20vw, 200px);
    background-color: #9C27B0;
}

Example 1: Using calc()

The box width is calculated as 50% of the container width minus 20px, and height is 100px plus 20px.

Example 2: Using min() and max()

The box width is the smaller value between 300px and 50% of the container width, and height is the larger value between 100px and 10% of the viewport width.

Example 3: Using clamp()

The box width is clamped between 150px and 300px, with a preferred value of 30% of the container width. Height is clamped between 100px and 200px, with a preferred value of 20% of the viewport width.