SyntaxStudy
Sign Up
SASS / SCSS Defining and Including Mixins
SASS / SCSS Beginner 1 min read

Defining and Including Mixins

A mixin is a reusable block of CSS declarations defined with `@mixin` and inserted into a rule with `@include`. Mixins solve the copy-paste problem: instead of writing the same group of vendor-prefixed properties or repeated declarations in multiple places, you define them once and include them wherever needed. Changing the mixin updates every place it is used. Mixins can accept arguments, making them parametric templates. Argument lists are defined in parentheses after the mixin name, optionally with default values using a colon. When including a mixin you pass arguments positionally or by name using the `$arg: value` syntax. Default values mean callers only need to supply the arguments they want to override. Unlike `%placeholder` selectors (used with `@extend`), each `@include` of a mixin outputs a full copy of the mixin body at the point of inclusion. This means mixins with arguments are ideal when you need slightly different output each time. For truly identical output shared across many selectors, `@extend` with placeholders is more efficient.
Example
// ── Defining mixins ───────────────────────────────────────────────────────────

// Simple mixin — no arguments
@mixin clearfix {
    &::after {
        content : '';
        display : table;
        clear   : both;
    }
}

// Mixin with required argument
@mixin size($width, $height) {
    width : $width;
    height: $height;
}

// Mixin with optional arguments (default values)
@mixin border-radius($radius: 4px) {
    -webkit-border-radius: $radius;
    -moz-border-radius   : $radius;
    border-radius        : $radius;
}

// Mixin with multiple defaults and named arguments
@mixin button-style(
    $bg       : #3498db,
    $color    : #fff,
    $padding  : 0.6rem 1.2rem,
    $radius   : 4px
) {
    display         : inline-flex;
    align-items     : center;
    justify-content : center;
    background-color: $bg;
    color           : $color;
    padding         : $padding;
    border-radius   : $radius;
    border          : none;
    cursor          : pointer;
    transition      : background-color 0.2s;

    &:hover { background-color: darken($bg, 10%); }
}

// ── Including mixins ──────────────────────────────────────────────────────────

.container { @include clearfix; }

.avatar    { @include size(48px, 48px); }

.card      { @include border-radius(8px); }

.btn-primary   { @include button-style; }  // all defaults
.btn-danger    { @include button-style($bg: #e74c3c); }
.btn-large     { @include button-style($padding: 0.9rem 2rem, $radius: 6px); }