CSS Functions and Mixins Module

Editor’s Draft,

More details about this document
This version:
https://drafts.csswg.org/css-mixins/
Latest published version:
https://www.w3.org/TR/css-mixins-1/
Feedback:
CSSWG Issues Repository
Editors:
Miriam E. Suzanne (Invited Expert)
Tab Atkins-Bittner (Google)
Suggest an Edit for this Spec:
GitHub Editor

Abstract

This module provides the ability to define custom functional notations.

CSS is a language for describing the rendering of structured documents (such as HTML and XML) on screen, on paper, etc.

Status of this document

This is a public copy of the editors’ draft. It is provided for discussion only and may change at any moment. Its publication here does not imply endorsement of its contents by W3C. Don’t cite this document other than as work in progress.

Please send feedback by filing issues in GitHub (preferred), including the spec code “css-mixins” in the title, like this: “[css-mixins] …summary of comment…”. All issues and comments are archived. Alternately, feedback can be sent to the (archived) public mailing list www-style@w3.org.

This document is governed by the 03 November 2023 W3C Process Document.

1. Introduction

This section is not normative.

Note: At this time, this specification only defines custom functions, which operate at the level of CSS values. It is expected that it will define "mixins" later, which are functions that operate at the style rule level.

Custom properties give authors a lot of power to define useful, sometimes complex values in one place, and then re-use them across their stylesheet. They can vary across the document, or based on Media Queries or other conditionals, making them very flexible and responsive.

However, their values are fixed at the point they’re defined, unable to be changed except by fully overriding their previous definition: a --shadow: 2px 2px var(--shadow-color) declaration takes its --shadow-color value from the element it’s declared on, and later changes to --shadow-color on descendant elements don’t alter the value of --shadow for them; they continue to use the shadow color defined where --shadow was defined. This is a common source of confusion for authors making heavy use of composite variables like this.

Custom functions allow authors the same power as custom properties, but parameterized: they have the same flexibility and conditionality as a custom property definition, but take values from other custom properties (or explicitly as arguments) at the point of use. For example, instead of a --shadow custom property, a --shadow() custom function could be defined instead, like:

@function --shadow(--shadow-color <color> : inherit) {
  /* If --shadow-color argument isn't passed,
     or doesn't successfully parse as a <color>,
     try to use the --shadow-color *property*
     from the element instead */

  /* var(--shadow-color) refers to the --shadow-color parameter,
     rather than a custom property,
     but can still use a fallback value as normal */
  result: 2px 2px var(--shadow-color, black);
}

.foo {
  --shadow-color: blue;
  box-shadow: --shadow(); /* produces a blue shadow */
  /* or just */
  box-shadow: --shadow(blue);
}

2. Defining Custom Functions

A custom function can be thought of as an advanced custom property, which instead of being substituted by a single fixed value, computes its substitution value based on function parameters and the value of custom properties at the point it’s invoked. Rather than the var() syntax that custom properties use for substitution, custom functions are invoked by <dashed-function> syntax, allowing additional values to be passed as arguments.

A simple custom function to negate a value can be defined as follows:
@function --negative(--value) {
  result: calc(-1 * var(--value));
}

Then, that function can be referenced with --negative() in some declaration:

html {
  --gap: 1em;
  padding: --negative(var(--gap));
  /* or by passing the value explicitly, like: */
  padding: --negative(1em);
}

<dashed-function>s are arbitrary substitution functions, like var(). Their presence in a property’s value causes it to be assumed valid at parse time, and only evaluated and parsed at computed-value time, after arbitrary substitution has occurred.

2.1. The @function Rule

The @function rule defines a custom function, and consists of a name, a list of parameters, a function body, and optionally a return type described by a syntax definition.

Each function parameter consists of a name (<custom-property-name>); optionally a parameter type, described by a syntax definition; and optionally a default value.

<@function> = @function <function-token> <function-parameter>#? )
  [ returns <css-type> ]?
{
  <declaration-rule-list>
}

<function-parameter> = <custom-property-name> <css-type>? [ : <declaration-value> ]?
<css-type> = <syntax-component> | <type()>
<type()> = type( <syntax> )

2.1.1. The Function Preamble

The <function-token> production must start with two dashes (U+002D HYPHEN-MINUS), similar to <dashed-ident>, or else the definition is invalid.

The name of the resulting custom function is given by the name of the <function-token>, the optional function parameters are given by the <function-parameter> values (defaulting to an empty set), and the optional return type is given by the <css-type> following the returns keyword (defaulting to *).

If the <css-type> of a function parameter or return type can be described by a single <syntax-component>, then the type() function can be omitted:
@function --foo(--a <length>) { /* ... */ }
@function --foo(--a <color>) { /* ... */ }
@function --foo(--a <length>+) { /* ... */ }

However, any <syntax> that requires a <syntax-combinator> needs to be wrapped in the type() function:

@function --foo(--a type(<number> | <percentage>)) { /* ... */ }

The name of a @function rule is a tree-scoped name. If more than one @function exists for a given name, then the rule in the stronger cascade layer wins, and rules defined later win within the same layer.

If the function parameters contain the same <custom-property-name> more than once, then the @function rule is invalid.

2.1.2. The Function Body

The body of a @function rule accepts conditional group rules, such as @media. Additionally, it accepts the following descriptors:

Unknown descriptors are invalid and ignored, but do not make the @function rule itself invalid.

2.2. The result Descriptor

Name: result
For: @function
Value: <declaration-value>?
Initial: n/a (see prose)

The result descriptor defines the result of evaluating the custom function defined by its @function rule. Using var() functions, it can reference function parameters, local variables, as well as other custom functions via <dashed-function>s.

The result descriptor itself does not have a type, but its resolved value is type-checked during the substitution of a <dashed-function>.

2.3. Arguments & Local Variables

This section is non-normative.

Within a custom function’s function body, the var() function can access local variables (the custom properties defined in the function body), function parameters (the values passed to the function, or set to default values), and custom properties defined at the call site (an element, or another custom function).

In that list, earlier things "win" over later things of the same name—​if you have a local variable named --foo, var(--foo) will be substituted by that local variable, not by an argument or a custom property defined outside. The other values can still be accessed, however: setting the --foo local variable to initial will resolve it to the --foo parameter, while inherit will resolve it to the --foo custom property from the call site.

A custom function can access local variables and function parameters from functions higher up in the call stack:
@function --outer(--outer-arg) {
  --outer-local: 2;
  result: --inner();
}
@function --inner() returns <number> {
  result: calc(var(--outer-arg) + var(--outer-local));
}
div {
  z-index: --outer(1); /* 3 */
}

Similarly, custom properties are implicitly available:

@function --double-z() returns <number> {
  result: calc(var(--z) * 2);
}
div {
  --z: 3;
  z-index: --double-z(); /* 6 */
}

But function parameters "shadow" custom properties, and local variables "shadow" both:

@function --add-a-b-c(--b, --c) {
  --c: 300;
  result: calc(var(--a) + var(--b) + var(--c));
  /* uses the --a from the call site's custom property,
     the --b from the function parameter,
     and the --c from the local variable */
}
div {
  --a: 1;
  --b: 2;
  --c: 3;
  z-index: --add-a-b-c(20, 30); /* 321 */
}

3. Using Custom Functions

Similar to how the value of a custom property can be substituted into the value of another property with var(), the result of a custom function evaluation can be substituted into the value of a property with a <dashed-function>.

A <dashed-function> is a functional notation whose function name starts with two dashes (U+002D HYPHEN-MINUS). Its syntax is:

<dashed-function> = --*( <declaration-value># )

A <dashed-function> can only be used where var() is allowed.

If a property contains one or more <dashed-function>s, the entire property’s grammar must be assumed to be valid at parse time. At computed-value time, every <dashed-function> must be substituted before finally being checked against the property’s grammar.

Note: Within the body of a custom function, var() functions might resolve differently than on the element the <dashed-function> is used on. See § 3.1 Evaluating Custom Functions.

A <dashed-function> is evaluated in some context: either in a property value on an element (or in a descriptor that is eventually treated like a property on an element, such as in @keyframes), or in a descriptor in the function body of another custom function that is being applied to a "hypothetical" element. Either way, this provides a calling context, which contains the property or descriptor name containing the <dashed-function>, and the element (or "hypothetical" element) that property/descriptor is being applied to.

As calling contexts are nested by <dashed-function> evaluations inside of custom functions, a calling context’s root element is the real element at the root of the calling context stack.

To substitute a dashed function in a value, with dashed function being a <dashed-function>:
  1. Let function be the result of dereferencing the dashed function’s name as a tree-scoped reference. If no such name exists, return failure.

  2. Substitute any arbitrary substitution functions within dashed function’s arguments, then parse it as <declaration-value># and let arguments be the result (a comma-separated list of CSS values).

  3. If dashed function is being substituted into a property on an element, let calling context be a calling context with that element and that property

    Otherwise, it’s being substituted into a descriptor on a "hypothetical element", while evaluating another custom function. Let calling context be a calling context with that "hypothetical element" and that descriptor.

  4. Evaluate a custom function, using function, arguments, and calling context, and replace the <dashed-function> with the equivalent token sequence of the value resulting from the evaluation.

If substitute a dashed function fails, and the substitution is taking place on a property’s value, then the declaration containing the <dashed-function> becomes invalid at computed-value time.

A comma-containing value may be passed as a single argument by wrapping the value in curly braces, {}:
@function --max-plus-x(--list, --x) {
  result: calc(max(var(--list)) + var(--x));
}
div {
  width: --max-plus-x({ 1px, 7px, 2px }, 3px); /* 10px */
}

3.1. Evaluating Custom Functions

Custom functions are evaluated by, essentially, pretending their function body is a style rule being applied to a hypothetical element, resolving styles as normal, and then returning the value of the result descriptor on that hypothetical element. The hypothetical element "inherits" the values of all custom properties as if it were a child of its calling context, with its function parameters overriding "inherited" custom properties of the same name.

To evaluate a custom function custom function, given a calling context calling context and a list of CSS values arguments, returning a CSS value:
  1. If the number of items in arguments is greater than the number of function parameters in custom function, return the guaranteed-invalid value.

  2. Let registrations be an initially empty set of custom property registrations.

  3. For each function parameter of custom function, create a custom property registration with the parameter’s name, a syntax of the parameter type, an inherit flag of "true", and no initial value. Add the registration to registrations.

  4. If custom function has a return type, create a custom property registration with the name "return" (violating the usual rules for what a registration’s name can be), a syntax of the return type, an inherit flag of "false", and no initial value. Add the registration to registrations.

  5. Let argument rule be an initially empty style rule.

  6. For each function parameter of custom function:

    1. Let arg value be the value of the corresponding argument in arguments, or the guaranteed-invalid value if there is no corresponding argument.

    2. Let default value be the parameter’s default value.

    3. Add a custom property to argument rule with a name of the parameter’s name, and a value of first-valid(arg value, default value).

  7. Resolve function styles using argument styles, registrations, and calling context. Let argument styles be the result.

  8. Let body rule be the function body of custom function, as a style rule.

  9. For each custom property registration of registrations, set its initial value to the corresponding value in argument styles, and prepend a custom property to body rule with the property name and value in argument styles.

  10. Resolve function styles using body rule, registrations, and calling context. Let body styles be the result.

  11. Return the value of the result property in body styles.

To resolve function styles, given a style rule rule, a set of custom property registrations registrations, and a calling context calling context, returning a set of computed styles:
  1. Create a "hypothetical element" el that acts as a child of calling context’s element. el is featureless, and only custom properties and the result descriptor apply to it.

  2. Apply rule to el to the specified value stage, with the following changes:

  3. Determine the computed value of all custom properties and the result "property" on el, as defined in CSS Properties and Values API 1 § 2.4 Computed Value-Time Behavior, with changes from the previous step, and the following:

    • Aside from references to custom properties (which use the values on el as normal) and numbers/percentages (which are left unresolved in custom properties, as normal), all values which would normally refer to the element being styled instead refer to calling context’s root element.

      Note: For example, attr() in a property, or @container queries in the rule.

  4. Return el’s styles.

    Note: Only custom properties and the result descriptor will be used from these styles.

3.2. Cycles

The result descriptor and local variables within a custom function may reference other custom functions or custom properties, and may therefore create cycles.

For each element, add a node for every specified custom function to the graph described in CSS Variables 1 § 2.3 Resolving Dependency Cycles; add a node for each local variable defined within each of those functions; then, for each custom function func, add edges as follows:

A <dashed-function> referencing a custom function which is part of a cycle makes the containing declaration invalid at computed-value time.

Note: Cycles are disallowed even through branches that are not taken during execution.

In the following, --foo() is in a cycle with itself, even though the media query never evaluates to "true":
@function --foo(--x) {
  @media (unknown-feature) {
    result: --foo(42);
  }
  result: 1;
}

Similarly, --bar() is in a cycle with itself, even though the local variable --x is never referenced:

@function --bar() {
  --x: --bar();
  result: 1;
}
The function --baz() is not in a cycle in the example below: even though var(--x) and var(--y) appear in the function body, they refer to a function parameter and local variable, respectively. The custom properties --x and --y both reference --baz(), but that’s fine: those custom properties are not referenced within --baz().
@function --baz(--x) {
  --y: 10px;
  result: calc(var(--x) + var(--y));
}

div {
  --x: --baz(1px);
  --y: --baz(2px);
  width: var(--x);  /* 11px */
  height: var(--y); /* 12px */
}

4. Execution Model of Custom Functions

Like the rest of CSS, custom functions adhere to a declarative model.

The local variable descriptors and result descriptor can appear in any order, and may be provided multiple times. If this happens, then declarations appearing later win over earlier ones.

@function --mypi() {
  result: 3;
  result: 3.14;
}

The value of the result descriptor of --mypi is 3.14.

@function --circle-area(--r) {
  result: calc(pi * var(--r2));
  --r2: var(--r) * var(--r);
}

Local variable descriptors may appear before or after they are referenced.

4.1. Conditional Rules

A conditional group rule that appears within a @function becomes a nested group rule, with the additional restriction that only descriptors allowed within @function are allowed within the nested group rule.

Conditional group rules within @function are processed as normal, acting as if the contents of the rule were present at the conditional group rule’s location when the condition is true, or acting as if nothing exists at that location otherwise.

@function --suitable-font-size() {
  result: 16px;
  @media (width > 1000px) {
    result: 20px;
  }
}

The value of the result descriptor is 20px if the media query’s condition is true, and 16px otherwise.

Note that due to the execution model, "early return" is not possible within a @function:
@function --suitable-font-size() {
  @media (width > 1000px) {
    result: 20px;
  }
  result: 16px;
}

The value of the result descriptor is always 16px in the above example.

Local variables are also valid within conditional rules:
@function --suitable-font-size() {
  --size: 16px;
  @media (width > 1000px) {
    --size: 20px;
  }
  result: var(--size);
}

5. CSSOM

The CSSFunctionRule interface represents a @function rule.

[Exposed=Window]
interface CSSFunctionRule : CSSGroupingRule { };

While declarations may be specified directly within a @function rule, they are not represented as such in the CSSOM. Instead, consecutive segments of declarations appear as if wrapped in CSSFunctionDeclarations rules.

Note: This also applies to the "leading" declarations in the @function rule, i.e those that do not follow another nested rule.

@function --bar() {
  --x: 42;
  result: var(--y);
  @media (width > 1000px) {
    /* ... */
  }
  --y: var(--x);
}

The above will appear in the CSSOM as:

@function --bar() {
  /* CSSFunctionDeclarations { */
    --x: 42;
    result: var(--y);
  /* } */
  @media (width > 1000px) {
    /* ... */
  }
  /* CSSFunctionDeclarations { */
    --y: var(--x);
  /* } */
}

5.1. The CSSFunctionDeclarations Interface

The CSSFunctionDeclarations interface represents a run of consecutive declarations within a @function rule.

[Exposed=Window]
interface CSSFunctionDescriptors : CSSStyleDeclaration {
  attribute [LegacyNullToEmptyString] CSSOMString result;
};

[Exposed=Window]
interface CSSFunctionDeclarations : CSSRule {
  [SameObject, PutForwards=cssText] readonly attribute CSSFunctionDescriptors style;
};
The style attribute must return a CSSFunctionDescriptors object for the rule, with the following properties:
computed flag

Unset

readonly flag

Unset

declarations

The declared declarations in the rule, in specified order. This includes any local variables.

parent CSS rule

this

owner node

Null

The CSSFunctionDeclarations rule, like CSSNestedDeclarations, serializes as if its declaration block had been serialized directly.

6. Privacy Considerations

The constructs defined by this specification are defined and used entirely within CSS; they expose no new information.

7. Security Considerations

No issues have been opened against this specification.

Conformance

Document conventions

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words “for example” or are set apart from the normative text with class="example", like this:

This is an example of an informative example.

Informative notes begin with the word “Note” and are set apart from the normative text with class="note", like this:

Note, this is an informative note.

Advisements are normative sections styled to evoke special attention and are set apart from other normative text with <strong class="advisement">, like this: UAs MUST provide an accessible alternative.

Tests

Tests relating to the content of this specification may be documented in “Tests” blocks like this one. Any such block is non-normative.


Conformance classes

Conformance to this specification is defined for three conformance classes:

style sheet
A CSS style sheet.
renderer
A UA that interprets the semantics of a style sheet and renders documents that use them.
authoring tool
A UA that writes a style sheet.

A style sheet is conformant to this specification if all of its statements that use syntax defined in this module are valid according to the generic CSS grammar and the individual grammars of each feature defined in this module.

A renderer is conformant to this specification if, in addition to interpreting the style sheet as defined by the appropriate specifications, it supports all the features defined by this specification by parsing them correctly and rendering the document accordingly. However, the inability of a UA to correctly render a document due to limitations of the device does not make the UA non-conformant. (For example, a UA is not required to render color on a monochrome monitor.)

An authoring tool is conformant to this specification if it writes style sheets that are syntactically correct according to the generic CSS grammar and the individual grammars of each feature in this module, and meet all other conformance requirements of style sheets as described in this module.

Partial implementations

So that authors can exploit the forward-compatible parsing rules to assign fallback values, CSS renderers must treat as invalid (and ignore as appropriate) any at-rules, properties, property values, keywords, and other syntactic constructs for which they have no usable level of support. In particular, user agents must not selectively ignore unsupported component values and honor supported values in a single multi-value property declaration: if any value is considered invalid (as unsupported values must be), CSS requires that the entire declaration be ignored.

Implementations of Unstable and Proprietary Features

To avoid clashes with future stable CSS features, the CSSWG recommends following best practices for the implementation of unstable features and proprietary extensions to CSS.

Non-experimental implementations

Once a specification reaches the Candidate Recommendation stage, non-experimental implementations are possible, and implementors should release an unprefixed implementation of any CR-level feature they can demonstrate to be correctly implemented according to spec.

To establish and maintain the interoperability of CSS across implementations, the CSS Working Group requests that non-experimental CSS renderers submit an implementation report (and, if necessary, the testcases used for that implementation report) to the W3C before releasing an unprefixed implementation of any CSS features. Testcases submitted to W3C are subject to review and correction by the CSS Working Group.

Further information on submitting testcases and implementation reports can be found from on the CSS Working Group’s website at http://www.w3.org/Style/CSS/Test/. Questions should be directed to the public-css-testsuite@w3.org mailing list.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[CSS-ANIMATIONS-1]
David Baron; et al. CSS Animations Level 1. URL: https://drafts.csswg.org/css-animations/
[CSS-CASCADE-5]
Elika Etemad; Miriam Suzanne; Tab Atkins Jr.. CSS Cascading and Inheritance Level 5. URL: https://drafts.csswg.org/css-cascade-5/
[CSS-CONDITIONAL-3]
Chris Lilley; David Baron; Elika Etemad. CSS Conditional Rules Module Level 3. URL: https://drafts.csswg.org/css-conditional-3/
[CSS-NESTING-1]
Tab Atkins Jr.; Adam Argyle. CSS Nesting Module. URL: https://drafts.csswg.org/css-nesting/
[CSS-PROPERTIES-VALUES-API-1]
Tab Atkins Jr.; Alan Stearns; Greg Whitworth. CSS Properties and Values API Level 1. URL: https://drafts.css-houdini.org/css-properties-values-api-1/
[CSS-SCOPING-1]
Tab Atkins Jr.; Elika Etemad. CSS Scoping Module Level 1. URL: https://drafts.csswg.org/css-scoping/
[CSS-SYNTAX-3]
Tab Atkins Jr.; Simon Sapin. CSS Syntax Module Level 3. URL: https://drafts.csswg.org/css-syntax/
[CSS-VALUES-4]
Tab Atkins Jr.; Elika Etemad. CSS Values and Units Module Level 4. URL: https://drafts.csswg.org/css-values-4/
[CSS-VALUES-5]
Tab Atkins Jr.; Elika Etemad; Miriam Suzanne. CSS Values and Units Module Level 5. URL: https://drafts.csswg.org/css-values-5/
[CSS-VARIABLES-1]
Tab Atkins Jr.. CSS Custom Properties for Cascading Variables Module Level 1. URL: https://drafts.csswg.org/css-variables/
[CSS-VARIABLES-2]
CSS Custom Properties for Cascading Variables Module Level 2. Editor's Draft. URL: https://drafts.csswg.org/css-variables-2/
[CSSOM-1]
Daniel Glazman; Emilio Cobos Álvarez. CSS Object Model (CSSOM). URL: https://drafts.csswg.org/cssom/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://datatracker.ietf.org/doc/html/rfc2119
[SELECTORS-3]
Tantek Çelik; et al. Selectors Level 3. URL: https://drafts.csswg.org/selectors-3/
[SELECTORS-4]
Elika Etemad; Tab Atkins Jr.. Selectors Level 4. URL: https://drafts.csswg.org/selectors/
[WEBIDL]
Edgar Chen; Timothy Gu. Web IDL Standard. Living Standard. URL: https://webidl.spec.whatwg.org/

Informative References

[CSS-CONDITIONAL-5]
Chris Lilley; et al. CSS Conditional Rules Module Level 5. URL: https://drafts.csswg.org/css-conditional-5/

Property Index

No properties defined.

@function Descriptors

Name Value Initial
result <declaration-value>? n/a (see prose)

IDL Index

[Exposed=Window]
interface CSSFunctionRule : CSSGroupingRule { };

[Exposed=Window]
interface CSSFunctionDescriptors : CSSStyleDeclaration {
  attribute [LegacyNullToEmptyString] CSSOMString result;
};

[Exposed=Window]
interface CSSFunctionDeclarations : CSSRule {
  [SameObject, PutForwards=cssText] readonly attribute CSSFunctionDescriptors style;
};