CSS Math Functions

One of CSS's most useful features is its math functions. These are unique CSS variables that allow front-end developers to natively do basic arithmetic and mathematical computations within their CSS stylesheets.

Some of the math functions available in CSS are:

calc() Function

This function allows you to perform simple math calculations, such as addition, subtraction, multiplication, and division

For example, you can use "calc()" to set the width of an element to be the width of its parent element minus 50 pixels:

.element {
	width: calc(100% - 50px);
}

max() Function

This function returns the largest value of the arguments provided.

For example, you can use "max()" to set the width of an element to the larger of two values:

.element {
	width: max(80%, 500px);
}

In this example, the width property will be set to the larger of 80% and 500px. If the viewport width is greater than 500px, the element will be set to 80% of the viewport width. If the viewport width is less than 500px, the element will be set to 500px.

min() Function

This function returns the smallest value of the arguments provided.

For example, you can use min() to set the font size of an element to the smaller of two values:

.element {
	width: min(100%, 500px);
}

In this example, the width property will be set to the smaller of 100% and 500px. If the viewport width is less than 500px, the element will be set to 100% of the viewport width. If the viewport width is greater than 500px, the element will be set to 500px.

clamp() Function

This function returns the middle value within a range of values between a defined minimum and a maximum.

The clamp() function takes three arguments: a minimum value, a preferred value, and a maximum allowed value.

.element {
	font-size: clamp(20px, 2em, 5vw);
}

In this example, the font-size property will be set to a value between 20px and 5vw. If the calculated value is less than 20px, it will be set to 20px. If it is greater than 5vw, it will be set to 5vw. Otherwise, it will be set to the preferred value 2em.

Note that math functions are only supported in modern browsers, so you may need to include vendor prefixes to ensure compatibility with older browsers.