CSS Mixins Module

CSS functions are a powerful tool for creating dynamic and reusable styles. They allow you to define styles based on the context in which they are used, making it easier to create responsive and flexible designs.

Getting Started

The @apply rule was a proposal for CSS that allowed authors to share a set of CSS declarations between rules, similar to mixins in CSS preprocessors like Sass. While @apply itself is not currently on the standards track for browsers, the concept of mixins is often achieved using CSS Custom Properties.

Here's how the @apply rule was envisioned, and how a similar effect can be achieved with custom properties:

Original @apply Proposal (Not Standard)

CSS
    :root {
  --my-theme-styles: {
    background-color: steelblue;
    color: white;
    padding: 10px;
    border-radius: 5px;
  };
}

.button {
  @apply --my-theme-styles;
  border: 1px solid navy; /* Additional specific style */
}

.panel {
  @apply --my-theme-styles;
  margin-bottom: 1em; /* Additional specific style */
}
  

In this hypothetical example, --my-theme-styles defines a block of styles that are then applied to .button and .panel.

Achieving a Similar Effect with Custom Properties (Standard)

While not a direct replacement for the block-based @apply, you can use custom properties to create reusable style snippets, though it's more verbose for multiple properties:

CSS
    :root {
  --button-bg-color: steelblue;
  --button-text-color: white;
  --button-padding: 10px;
  --button-border-radius: 5px;
}

.button {
  background-color: var(--button-bg-color);
  color: var(--button-text-color);
  padding: var(--button-padding);
  border-radius: var(--button-border-radius);
  border: 1px solid navy;
}

.panel {
  background-color: var(--button-bg-color); /* Reusing some properties */
  color: var(--button-text-color);
  padding: var(--button-padding);
  border-radius: var(--button-border-radius);
  margin-bottom: 1em;
}
  

For more complex mixin-like behavior, developers often rely on CSS preprocessors or JavaScript-based solutions. The CSS Houdini APIs (like CSS Properties and Values API) also open up new possibilities for dynamic styling that can sometimes serve similar purposes.

Back to Features

Links

Chrome Status CSS Mixins (CSSWG)