Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

@function — a custom CSS value function

The experimental @function rule defines a parameterized CSS function whose result can be substituted into a property value.

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

Syntax

@function <prelude> { <rule-list> }

@function --name(<parameters>) [returns <type>]? { ... } defines a function whose name starts with --. Each parameter has a custom-property name, optional type, and optional default. The result descriptor supplies the returned value; without it the function returns the guaranteed-invalid value. A declared return type validates result before substitution.

A --name(arguments) call is allowed where var() is allowed and is evaluated at computed-value time. Parameters shadow same-named custom properties, while local variables in the body shadow parameters. Cycles, too many arguments, type failures, or a missing required value make substitution invalid and can invalidate the containing property at computed-value time.

Function names are tree-scoped; among duplicate definitions the stronger cascade layer wins, then the later rule within a layer. This is a CSSWG editor’s draft, so target-browser support needs explicit testing. The example defines typed --double(), turns opacity 0.3 into 0.6, and reads the actual computed value.

Examples

const style = document.createElement('style');
style.textContent = `@function --double(--value <number>) returns <number> { result: calc(var(--value) * 2); }
.probe { opacity: --double(0.3); }`;
document.head.append(style);
const probe = document.createElement('div');
probe.className = 'probe';
probe.textContent = 'CKTIS';
document.body.append(probe);
const rule = style.sheet.cssRules[0];
console.log('rules=' + style.sheet.cssRules.length + '; first=' + rule.constructor.name + '; opacity=' + getComputedStyle(probe).opacity);

Result

rules=2; first=CSSFunctionRule; opacity=0.6

The experimental @function rule defines a parameterized CSS function whose result can be substituted into a property value.

Sources