Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

calc() — CSS value arithmetic

`calc()` evaluates a numeric expression in the property’s calculation context, so it can combine compatible types whose units cannot be reduced to one number in advance.

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

Syntax

calc( <calc-sum> )

calc() evaluates a numeric expression in the property’s calculation context, so it can combine compatible types whose units cannot be reduced to one number in advance.

Inside a 300px container, the example applies width: calc(50% + 20px) and measures the used value 170px. The fallback declaration width: 33px survives because the later calc(10px + 1s) attempts to add a length to a time and is type-invalid.

Grammar: calc( <calc-sum> ).

Operators * and / bind more tightly than + and -; parentheses alter that order. Whitespace around binary + and - matters for tokenization. A percentage inherits the property’s context, so a width percentage can combine with a length once its percentage basis is known. Algebraically cancelling a term does not repair incompatible types.

Examples

const host=document.createElement('div'),mixed=document.createElement('div'),invalid=document.createElement('div');document.body.append(host);host.append(mixed,invalid);host.style.cssText='width:300px';mixed.style.cssText='width:calc(50% + 20px);height:1px';invalid.style.cssText='width:33px;width:calc(10px + 1s);height:1px';const mixedWidth=getComputedStyle(mixed).width,invalidWidth=getComputedStyle(invalid).width,invalidKept=invalid.style.width;if(mixedWidth!=='170px'||invalidWidth!=='33px'||invalidKept!=='33px')throw new Error('calc used-value/type boundary mismatch: '+[mixedWidth,invalidWidth,invalidKept]);console.log('mixed-used='+mixedWidth+'; invalid-fallback='+invalidWidth+'; declaration='+invalidKept);

Result

mixed-used=170px; invalid-fallback=33px; declaration=33px

`calc()` evaluates a numeric expression in the property’s calculation context, so it can combine compatible types whose units cannot be reduced to one number in advance.

Sources