CSS @apply At-Rule

The @apply at-rule applies a custom CSS mixin to a style rule. The mixin is defined with the @mixin at-rule and referenced by its dashed identifier or dashed function name.

@apply Syntax

@apply --mixin-name;
@apply --mixin-name(arguments);
@apply --mixin-name {
  declarations
}

The @apply at-rule accepts either a dashed identifier or a dashed function. An optional declaration block can also be supplied as content for the mixin.

How @apply Works

A mixin is defined with @mixin and given a custom name beginning with two hyphens. The @apply at-rule invokes that mixin and effectively substitutes the mixin's result at the location of the @apply rule.

@mixin --card {
  padding: 20px;
  border: 1px solid #777;
}
.card {
  @apply --card;
}

If the referenced mixin does not exist, the @apply rule has no effect. The at-rule is valid within the body of a style rule or nested group rule and is invalid when used at the top level of a style sheet.

Using Arguments

A mixin can define parameters. When the mixin is applied, values can be supplied as arguments using the dashed function form.

@mixin --spacing(--amount <length>) {
  padding: var(--amount);
}
.box {
  @apply --spacing(20px);
}

The arguments supplied by @apply are matched to the parameters defined by the mixin. A mixin without arguments can be invoked using either its dashed identifier or an empty function call.

Content Blocks

The @apply at-rule can pass a declaration block to a mixin. The mixin can insert that block through the @contents at-rule.

@mixin --wide-screen {
  @media (width > 800px) {
    @contents;
  }
}
.example {
  @apply --wide-screen {
    display: grid;
    grid-template-columns: 1fr 1fr;
  }
}

This allows a mixin to provide reusable structure or conditions while the @apply rule supplies declarations specific to the style rule where the mixin is used.

@apply Example

The following example defines a reusable mixin and applies it to two style rules.

@mixin --panel {
  padding: 20px;
  border: 1px solid #777;
  border-radius: 6px;
}
.notice {
  @apply --panel;
}
.example {
  @apply --panel;
}

Both style rules apply the declarations defined by the --panel mixin without repeating those declarations in each rule.

Specifications

The @apply at-rule is currently defined in the CSS Custom Functions and Mixins Module Level 1. Its syntax and behavior may change as the specification develops.

CSS Custom Functions and Mixins Module Level 1 - The @apply Rule