clamp() - CSS: Cascading Style Sheets | MDN (2024)

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2020.

The clamp() CSS function clamps a middle value within a range of values between a defined minimum bound and a maximum bound. The function takes three parameters: a minimum value, a preferred value, and a maximum allowed value.

Try it

Note that using clamp() for font sizes, as in these examples, allows you to set a font-size that grows with the size of the viewport, but doesn't go below a minimum font-size or above a maximum font-size. It has the same effect as the code in Fluid Typography but in one line, and without the use of media queries.

Syntax

css

/* Static values */width: clamp(200px, 40%, 400px);width: clamp(20rem, 30vw, 70rem);width: clamp(10vw, 20em, 100vw);/* Calculated values */width: clamp(min(10vw, 20rem), 300px, max(90vw, 55rem));width: clamp(100px, calc(30% / 2rem + 10px), 900px);

Parameters

The clamp(min, val, max) function accepts three comma-separated expressions as its parameters.

min

The minimum value is the smallest (most negative) value. This is the lower bound in the range of allowed values. If the preferred value is less than this value, the minimum value will be used.

val

The preferred value is the expression whose value will be used as long as the result is between the minimum and maximum values.

max

The maximum value is the largest (most positive) expression value to which the value of the property will be assigned if the preferred value is greater than this upper bound.

The expressions can be math functions (see calc() for more information), literal values, other expressions that evaluate to a valid argument type (like <length>), or nested min() and max() functions. For math expressions, you can use addition, subtraction, multiplication, and division without using the calc() function itself. You may also use parentheses to establish computation order when needed.

You can use different units for each value in your expressions and different units in any math function making up any of the arguments.

Keep the following aspects in mind while working with the function:

  • Math expressions involving percentages for widths and heights on table columns, table column groups, table rows, table row groups, and table cells in both auto and fixed layout tables may be treated as if auto had been specified.
  • It is permitted to nest max() and min() functions as expression values, in which case the inner ones are treated as simple parentheses. The expressions are full math expressions, so you can use direct addition, subtraction, multiplication and division without using the calc() function itself.
  • The expression can be values combining the addition ( + ), subtraction ( - ), multiplication ( * ) and division ( / ) operators, using standard operator precedence rules. Make sure to put a space on each side of the + and - operands. The operands in the expression may be any <length> syntax value. You can use different units for each value in your expression. You may also use parentheses to establish computation order when needed.
  • Oftentimes you will want to use min() and max() within a clamp() function.

Return value

clamp(MIN, VAL, MAX) is resolved as max(MIN, min(VAL, MAX)).

Based on the provided parameters, the function returns <length>, <frequency>, <angle>, <time>, <percentage>, <number>, or <integer>.

Formal syntax

<clamp()> = 
clamp( [ <calc-sum> | none ] , <calc-sum> , [ <calc-sum> | none ] )

<calc-sum> =
<calc-product> [ [ '+' | '-' ] <calc-product> ]*

<calc-product> =
<calc-value> [ [ '*' | '/' ] <calc-value> ]*

<calc-value> =
<number> |
<dimension> |
<percentage> |
<calc-keyword> |
( <calc-sum> )

<calc-keyword> =
e |
pi |
infinity |
-infinity |
NaN

Examples

min(), max(), and clamp() comparison

In this example we have a web page that uses min(), max(), and clamp() to set sizes responsively.

The example adjusts the sizes of page elements in three ways:

  • the lengths of the lines of text
  • the font size of paragraph text
  • the font size of heading text

In all three cases, the page uses a combination of a viewport-relative units (vw and <percentage>), to set a size that varies with the viewport width, and a value that is not viewport relative (rem and px) to implement minimum and/or maximum sizes.

The example is at https://mdn.github.io/css-examples/min-max-clamp/. Open it in a new window and try adjusting the window width.

The line length (controlled by the width of the <body> element) will increase as the window width increases, but only up to a certain point (1000px), and beyond that point, it won't increase anymore. We're using min() to set a maximum line length: it can go under 1000px, but won't go over. This is helpful because long lines are harder to read, so we often want to limit how long a line can be. To achieve this we use min(1000px, calc(70% + 100px)): when the result of the percentage-based calculation goes above 1000px, we switch to the fixed 1000px value.

The size of the paragraph text, controlled by the font-size of the <p> element, decreases as the window gets narrower, but only up to a certain point, and beyond that point (the point where 1.2vw is less than 1.2rem) it doesn't get any smaller: it stays at 1.2rem. We're using max() to set a minimum font size: the font can grow above 1.2rem but will never go below it. This is helpful because really small text is hard to read. To achieve this we use max(1.2rem, 1.2vw). This means that the font-size will be set at 1.2rem, unless the computed value of 1.2vw is greater than that of 1.2rem, in which case it will be set to 1.2vw instead.

The size of the heading text, controlled by the font-size of the <h1> element, has a viewport-relative value with both a maximum and a minimum threshold. To achieve this we use clamp(1.8rem, 2.5vw, 2.8rem). The viewport-relative value is 2.5vw but it is clamped between 1.8rem and 2.8rem, so:

  • if the calculated value of 2.5vw is less than 1.8rem, then 1.8rem will be used
  • if the calculated value of 2.5vw is greater than 2.8rem, then 2.8rem will be used.

This prevents the heading text from getting too small in a very narrow window, or too big in a very wide window.

HTML

html

<h1>Simple responsive test</h1><p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. In orci orci, eleifend id risus nec, mattis rutrum velit. Suspendisse fringilla egestas erat eu convallis. Phasellus eu velit ut magna dapibus elementum cursus at ligula. Ut tempus varius nibh, nec auctor sapien iaculis sit amet. Fusce iaculis, libero quis elementum viverra, nulla ante acc*msan lectus, sit amet convallis lacus ipsum vel est. Curabitur et urna non est consectetur pulvinar vel id risus. Ut vestibulum, sem in semper aliquet, felis arcu euismod sapien, ac imperdiet massa nisl quis sem. Vestibulum ac elementum felis, in tempor velit. Pellentesque purus ex, mattis at ornare quis, porta condimentum mi. Donec vestibulum ligula vel nulla blandit, quis euismod nulla vestibulum. Suspendisse potenti. Nunc neque mauris, tempor sed facilisis at, ultrices eget nulla. Pellentesque convallis ante nec augue porttitor, id tempus ante luctus.</p><p> Integer rutrum sollicitudin tellus, quis cursus nulla scelerisque nec. Nunc eu facilisis lorem. Maecenas faucibus sapien eleifend, semper tellus at, pharetra quam. Cras feugiat vulputate tortor at rhoncus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam non felis quis sem lobortis sodales vel id libero. Phasellus sit amet placerat lorem.</p>

CSS

css

html { font-family: sans-serif;}body { margin: 0 auto; width: min(1000px, calc(70% + 100px));}h1 { letter-spacing: 2px; font-size: clamp(1.8rem, 2.5vw, 2.8rem);}p { line-height: 1.5; font-size: max(1.2rem, 1.2vw);}

Specifications

Specification
CSS Values and Units Module Level 4
# calc-notation

Browser compatibility

BCD tables only load in the browser

See also

  • calc()
  • max()
  • min()
  • CSS Values
clamp() - CSS: Cascading Style Sheets | MDN (2024)

FAQs

What is clamp () in CSS? ›

The clamp() CSS function clamps a middle value within a range of values between a defined minimum bound and a maximum bound. The function takes three parameters: a minimum value, a preferred value, and a maximum allowed value.

How does clamp() work? ›

CSS clamp function takes three values — a minimum bound, preferred value, and a maximum bound, and it clamps the current value between those bounds. The preferred value is used to determine the value between the bound.

Should I use clamp CSS? ›

Why use the CSS Clamp() Function? There are several benefits of using the CSS clamp() function, including: Improved Flexibility: The clamp() function provides a more flexible and concise way of controlling the size of an element, as opposed to using multiple media queries or JavaScript.

What does a clamp do? ›

A clamp function specifies a range of values. Values below the minimum are set to the minimum. Values above the maximum are set to the maximum. Also, values within the range return themselves.

What are clamps used for ___________? ›

Clamps are versatile tools that serve to temporarily hold work securely in place. They are used for many applications including carpentry, woodworking, furniture making, welding, construction and metal working.

Why is clamping used? ›

Clamping can be used to adapt an input signal to a device that cannot make use of or may be damaged by the signal range of the original input.

What does a clamp do in C? ›

Use Clamp to restrict a value to a range that is defined by the minimum and maximum values. Returns an undefined value if the minimum value is greater than the maximum value.

What is the working principle of clamp? ›

Clamp Meter Working Principle

The working principle of clamp meter is the magnetic induction principle to create AC current measurements without contact. The flow of current throughout a wire generates a magnetic field.

How to use CSS clamp for font size? ›

Here's a basic syntax for CSS Clamp: property: clamp( minimum, preferred, maximum ); For example, you can use clamp(16px, 5vw, 24px) for font size. This means the font size will be a minimum of 16 pixels, a preferred size of 5 viewport width units (vw), and a maximum of 24 pixels.

How does CSS clip work? ›

The clip property lets you specify a rectangle to clip an absolutely positioned element. The rectangle is specified as four coordinates, all from the top-left corner of the element to be clipped. Note: The clip property does not work if "overflow:visible".

What is line clamp CSS? ›

The line-clamp CSS property allows limiting of the contents of a block container to the specified number of lines.

Why are clamps needed? ›

You need clamps to hold something temporarily or permanently in place. Here are some of the most useful kinds of clamps. All clamps serve the same purpose: to hold things securely. But you might be surprised at how many different varieties of clamps there are.

What is the purpose of the work clamp? ›

A work lead clamp is perhaps the common method to connect the work lead cable to the workpiece. The work lead clamp is bolted to the lug at the end of the work lead cable and has brass or copper jaws to ensure good electrical contact to the workpiece.

What is clamp in programming? ›

In computer science, clamping, or clipping is the process of limiting a value to a range between a minimum and a maximum value. Unlike wrapping, clamping merely moves the point to the nearest available value.

What is the purpose of the clamping element? ›

Clamping elements are used to clamp workpieces in fixtures for machine tool production. A variety of components hold the workpiece in position for CNC machining. Ideal for fixture construction and machine tool manufacturing.

What does it mean to clamp a value? ›

In computer science, we use the word clamp as a way to restrict a number between two other numbers.

What does clamp mean in code? ›

The clamp() function restricts a given value between an upper and lower bound. In this way, it acts like a combination of the min() and max() functions.

Top Articles
Latest Posts
Article information

Author: Jeremiah Abshire

Last Updated:

Views: 5766

Rating: 4.3 / 5 (54 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Jeremiah Abshire

Birthday: 1993-09-14

Address: Apt. 425 92748 Jannie Centers, Port Nikitaville, VT 82110

Phone: +8096210939894

Job: Lead Healthcare Manager

Hobby: Watching movies, Watching movies, Knapping, LARPing, Coffee roasting, Lacemaking, Gaming

Introduction: My name is Jeremiah Abshire, I am a outstanding, kind, clever, hilarious, curious, hilarious, outstanding person who loves writing and wants to share my knowledge and understanding with you.