SyntaxStudy
Sign Up
SASS / SCSS Mixins with @content for Block Passing
SASS / SCSS Beginner 1 min read

Mixins with @content for Block Passing

SASS mixins support a special `@content` directive that acts as a placeholder for a block of styles passed when the mixin is included. This transforms the mixin into a wrapping context — similar to how higher-order functions work in programming. The caller passes a block using curly braces after the `@include`, and that block is injected wherever `@content` appears in the mixin body. The most common use case for `@content` is media query mixins. You define a `respond-to` mixin that wraps its content in the appropriate `@media` rule. Callers write `@include respond-to("mobile") { font-size: 0.875rem; }`, keeping responsive adjustments co-located with their base styles rather than scattered in a separate media query section at the bottom of the file. Content blocks can also receive arguments passed from the mixin using `@content($value)`, and the caller captures them with `using ($var)`. This advanced pattern is useful for writing mixins that iterate over data and expose each item to the caller's content block, enabling flexible and dynamic stylesheet generation.
Example
// ── Breakpoint mixin using @content ───────────────────────────────────────────

$breakpoints: (
    'xs' : 480px,
    'sm' : 640px,
    'md' : 768px,
    'lg' : 1024px,
    'xl' : 1280px
);

@mixin respond-to($bp) {
    $value: map.get($breakpoints, $bp);

    @if $value == null {
        @warn "Unknown breakpoint `#{$bp}`.";
    } @else {
        @media (min-width: $value) {
            @content;  // caller's block goes here
        }
    }
}

// Usage — responsive styles stay with their component
.hero__title {
    font-size: 1.5rem;

    @include respond-to('md') { font-size: 2.25rem; }
    @include respond-to('lg') { font-size: 3rem; }
}

// ── @content with arguments (passing data to the content block) ───────────────

$themes: (
    'light': (#fff, #333),
    'dark' : (#1a1a2e, #e0e0e0)
);

@mixin apply-themes {
    @each $name, $colors in $themes {
        $bg   : nth($colors, 1);
        $text : nth($colors, 2);

        [data-theme="#{$name}"] {
            @content($bg, $text);  // pass bg + text to caller
        }
    }
}

.card {
    border-radius: 8px;
    padding      : 1.5rem;

    // using clause captures the mixin's content arguments
    @include apply-themes using ($bg, $text) {
        background: $bg;
        color     : $text;
    }
}