Content Blocks (@content)
Let a mixin wrap a block of styles you pass in.
Syntax
@mixin name { @content; } @include name { /* styles */ }The @content directive lets a mixin accept a block of styles from the caller and inject it at a chosen spot. This is perfect for wrappers like media queries and feature blocks.
The caller passes the block with braces after @include. Inside the mixin, @content marks where that block is placed.
Example
@use 'sass:map';
$breakpoints: ('tablet': 768px, 'desktop': 1024px);
@mixin respond-to($name) {
@media (min-width: map.get($breakpoints, $name)) {
@content;
}
}
.sidebar {
display: none;
@include respond-to('tablet') {
display: block;
}
}
/* @media (min-width: 768px) { .sidebar { display: block; } } */When to use it
- A media query mixin uses @content to wrap any block of styles the caller provides in the correct breakpoint without hardcoding the inner rules.
- A hover-state mixin wraps @content in a &:hover block so components can add any hover styles by passing a block to the mixin.
- A theme mixin applies a .dark-mode selector around @content, letting any component define its dark styles through the shared mixin interface.
More examples
Media query mixin with @content
The above() mixin accepts a pixel value and wraps the caller's @content block in the appropriate min-width media query.
@mixin above($px) {
@media (min-width: $px) {
@content;
}
}
.hero {
font-size: 1.5rem;
@include above(768px) {
font-size: 2.5rem;
text-align: center;
}
}Dark-mode wrapper mixin
A dark() mixin wraps @content in a prefers-color-scheme media query, co-locating dark-mode overrides with each component's base styles.
@mixin dark {
@media (prefers-color-scheme: dark) {
@content;
}
}
.card {
background: white;
color: #111;
@include dark {
background: #1e293b;
color: #f1f5f9;
}
}Hover block mixin
Wraps @content in both a hover media query and the :hover pseudo-class so touch devices never get stuck hover states.
@mixin on-hover {
@media (hover: hover) {
&:hover {
@content;
}
}
}
.btn {
background: #2563eb;
@include on-hover {
background: #1d4ed8;
transform: translateY(-1px);
}
}
Discussion