Mixins
A mixin is a named, reusable block of styles — define it once with @mixin, then drop it into as many selectors as you want with @include, optionally passing in arguments to change what it produces each time.
Defining and including a mixin
@mixin flex-center {
display: flex;
align-items: center;
justify-content: center;
}
.card {
@include flex-center;
height: 200px;
}
.modal {
@include flex-center;
height: 100vh;
}
.card {
display: flex;
align-items: center;
justify-content: center;
height: 200px;
}
.modal {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}The three flex-center properties get copied into every selector that includes it — write the centering logic once, use it anywhere.
Mixins with arguments
A mixin can take parameters, including default values, which makes it flexible instead of one fixed block of styles:
@mixin flex-center($direction: row, $gap: 0) {
display: flex;
align-items: center;
justify-content: center;
flex-direction: $direction;
gap: $gap;
}
.toolbar {
@include flex-center;
}
.sidebar-nav {
@include flex-center($direction: column, $gap: 12px);
}
.toolbar {
display: flex;
align-items: center;
justify-content: center;
flex-direction: row;
gap: 0;
}
.sidebar-nav {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
gap: 12px;
}.toolbar takes the mixin's defaults (row, no gap), while .sidebar-nav overrides both by passing named arguments — the same mixin produces two genuinely different results depending on what's handed to it.
A mixin with a content block
Passing @content lets a mixin wrap around a block of styles you supply at the call site — useful for repeated patterns like a media query:
@mixin on-mobile {
@media (max-width: 600px) {
@content;
}
}
.sidebar {
width: 250px;
@include on-mobile {
width: 100%;
}
}
.sidebar {
width: 250px;
}
@media (max-width: 600px) {
.sidebar {
width: 100%;
}
}@extend (covered in lesson 7), a mixin's properties are copied into every single selector that includes it — ten selectors including the same 5-property mixin means those 5 properties appear ten separate times in the compiled CSS. For a handful of uses this is completely fine; for something included hundreds of times across a large stylesheet, that duplication can meaningfully bloat the compiled file size.