How to use max() function in CSS

CSS is a styling language that helps us change the appearance of our HTML document. Multiple functions in CSS help us make styling decisions wisely.

max() function

The max() function allows us to set a CSS property value based on the maximum of two values. We can use the max() function to specify the maximum value for properties like width, height, font size, animation duration, and more where a length, integer, time, percentage, number, frequency, or angle value is accepted.

Usage

It provides flexibility in setting CSS property values giving us more control. It is beneficial in creating responsive layouts and setting property values as the maximum of multiple values based on our available space and circumstances. For example, we can use max() to set the height of an element based on the maximum value between a pixel value and a percentage value. This allows the element to scale responsively based on the available container space.

Support

The following table shows the browser and its versions that support the max() function.

Table showing browser versions supporting max() function

Browser

Version

Chrome

>= 79.0

Edge

>= 79.0

Firefox

>= 75.0

Opera

>= 66.0

Safari

>= 11.1

Syntax

The syntax of max() function is following:

#ElementID {
propety: max(firstValue, secondValue);
}
Syntax of max() function
  • #ElementID: It represents the HTML element's ID we are setting CSS for.

  • property: It represents the CSS property we want to apply CSS on, such as width or height etc.

  • max(firstValue, secondValue): We use the max() function to set the value of the property. The value of our property will be the maximum of the two values: firstValue and secondValue. We can have more than two arguments as well.

Example

The following code demonstrates how to use the max() function:

Let's understand what happens in the styles.css file:

  • Line 1: We specify we are applying CSS to the element with id myDiv.

  • Line 2: We set the background color of our element.

  • Line 3: We set the height of our element.

  • Line 4: We use the max() function to define the width of our element. It takes two arguments: 50% and 400px. The function selects the larger value between the two. In our case, 400px is greater than the 50% of our parent container's width, so we set the width to 400px.

Conclusion

The max() function in CSS is a convenient option to set a property's value that is the maximum between two or more values. It helps where our design decisions are based on the available space or desired constraints. We can create responsive and flexible designs using this function.

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved