Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

clamp() — constraining a value to a range

`clamp()` selects the preferred value but no less than the minimum and no more than the maximum; all arguments must have a consistent calculation type.

Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required

Syntax

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

clamp() selects the preferred value but no less than the minimum and no more than the maximum; all arguments must have a consistent calculation type.

In a 400px container the example measures all three branches: clamp(100px, 10%, 200px) yields 100px, clamp(100px, 40%, 200px) yields 160px, and clamp(100px, 80%, 200px) yields 200px. Boundary clamp(200px, 150px, 100px) also yields 200px.

Grammar: clamp( [ <calc-sum> | none ], <calc-sum>, [ <calc-sum> | none ] ).

Its semantics are max(MIN, min(VAL, MAX)), so the minimum wins when the bounds are inverted, not the maximum. Either bound may be none to remove clamping on that side. Each argument permits a full expression without an extra calc(), but inconsistent types invalidate the entire function.

Examples

const host=document.createElement('div');document.body.append(host);host.style.cssText='width:400px';const used=value=>{const box=document.createElement('div');host.append(box);box.style.cssText='height:1px;width:'+value;return Math.round(box.getBoundingClientRect().width)};const low=used('clamp(100px, 10%, 200px)'),preferred=used('clamp(100px, 40%, 200px)'),high=used('clamp(100px, 80%, 200px)'),inverted=used('clamp(200px, 150px, 100px)');if(low!==100||preferred!==160||high!==200||inverted!==200)throw new Error('clamp branch mismatch: '+[low,preferred,high,inverted]);console.log('min='+low+'; preferred='+preferred+'; max='+high+'; inverted='+inverted);

Result

min=100; preferred=160; max=200; inverted=200

`clamp()` selects the preferred value but no less than the minimum and no more than the maximum; all arguments must have a consistent calculation type.

Sources