Mixin Basics

Define reusable blocks of declarations with @mixin and @include.

Syntax@mixin name { declarations } @include name;

A mixin is a named, reusable group of CSS declarations. Define it with @mixin and drop it into any rule with @include.

Mixins are the primary tool for reusing chunks of style — vendor prefixes, common layout patterns, typography presets, and more. Unlike variables, which store a single value, a mixin stores whole declarations.

Example

Example · css
@mixin flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.hero {
  @include flex-center;
  height: 300px;
}
.modal {
  @include flex-center;
}

/* Both rules get display:flex; align-items:center; justify-content:center; */

When to use it

  • A developer defines a clearfix mixin once and @include-s it on every floated container layout throughout the project.
  • A team creates a visually-hidden mixin for accessible off-screen text and reuses it for skip-links and screen-reader-only labels across dozens of components.
  • A developer packages all vendor-prefixed CSS transform rules into a single mixin so they never have to remember which prefixes each browser needs.

More examples

Defining and including a mixin

Defines a screen-reader-only mixin and includes it in .sr-only, centralizing the visually-hidden pattern in one reusable place.

Example · css
@mixin visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip: rect(0 0 0 0);
  white-space: nowrap;
}

.sr-only {
  @include visually-hidden;
}

Clearfix mixin

Packages the classic float-clearing pseudo-element pattern into a mixin that any container can include without repeating the code.

Example · css
@mixin clearfix {
  &::after {
    content: '';
    display: table;
    clear: both;
  }
}

.container {
  @include clearfix;
}

Multiple components sharing a mixin

Three different card components all @include the same base mixin and add their own unique properties on top.

Example · css
@mixin card-base {
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0,0,0,.1);
  overflow: hidden;
}

.product-card  { @include card-base; width: 240px; }
.profile-card  { @include card-base; width: 320px; }
.dashboard-widget { @include card-base; }

Discussion

  • Be the first to comment on this lesson.