max() CSS Function

Description

The CSS max() function returns the largest value from a comma-separated list of values. It can be used to set the maximum value of any CSS property that accepts a <length>, <frequency>, <angle>, <time>, <percentage>, <number>, or <integer>.

The max() function takes one or more expressions as its parameters. The expressions can be math expressions (using arithmetic operators), literal values, or other expressions, such as attr(), that evaluate to a valid argument type. You can use different units for each value in your expression. You may also use parentheses to establish computation order when needed.

For example, the following CSS code will set the maximum width of the element to the larger of 100px or 50vw:

.element {
  max-width: max(100px, 50vw);
}

This can be useful for creating responsive designs that look good on all devices, regardless of screen size.

Here are some other examples of how to use the max() function:

  • To set the maximum height of an image:
img {
  max-height: 100%;
}
  • To set the maximum font size of a heading:
h1 {
  max-font-size: 2rem;
}
  • To set the maximum margin between two elements:
.element1,
.element2 {
  margin: 0 1rem;
}

@media (max-width: 768px) {
  .element1,
  .element2 {
    max-margin: 0.5rem;
  }
}

Syntax

&lt;max()&gt; = max( value1, value2, ... )

Values

  • value1, value2, ...A list of comma-separated values - where the largest value is chosen. Required.

Example

<h1>The max() Function</h1>

<p>Use max() to set the width of #div1 to whichever value is largest, 50% or 300px:</p>

<div id="div1">Some text...</div>

<p>Resize the browser window to see the effect.</p>
#div1 {
background-color: yellow;
height: 100px;
width: max(50%, 300px);
}

Browser Support

The following table will show you the current browser support for the CSS max() function.

Desktop
Edge Chrome Firefox Opera Safari
7979756611.1
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
79795711.31279

Last updated by CSSPortal on: 7th October 2023