SCSS by Example: Mixins
Creating reusable CSS declaration blocks with this code example demonstrating mixin definition using @mixin directive, parameterized mixins with arguments, mixin inclusion with @include, and vendor prefix automation.
Code
// Define a mixin
@mixin flex-center {
display: flex;
justify-content: center;
align-items: center;
}
// Mixin with arguments
@mixin border-radius($radius) {
-webkit-border-radius: $radius;
-moz-border-radius: $radius;
-ms-border-radius: $radius;
border-radius: $radius;
}
.card {
@include flex-center;
@include border-radius(8px);
width: 300px;
height: 200px;
}
.button {
@include border-radius(4px);
}Explanation
Mixins are defined using the @mixin directive and included using @include, allowing groups of CSS declarations to be reused throughout a stylesheet. When a mixin is included, its entire contents are copied into the selector at compile time. Unlike functions which return a single value, mixins output complete CSS rules and can contain selectors, properties, and even other mixins.
Mixins support parameters with optional default values, making them dynamic and flexible. Arguments can be positional or named using keyword syntax like @include mixin-name($arg1: value). Variable arguments using $args... allow mixins to accept an arbitrary number of parameters. Mixins can also use @content directive to accept entire blocks of styles passed from the include site, enabling powerful patterns like media query wrappers.
The compilation process expands each @include statement by copying the mixin's declarations directly into the calling selector. This means mixins can increase CSS file size if used extensively, as the same declarations are duplicated at each inclusion point. For vendor prefixes, mixins provide a centralized way to handle browser compatibility, though modern autoprefixer tools have largely replaced this use case.
Code Breakdown
@mixin flex-center defines reusable declaration block without parameters.@mixin border-radius($radius) accepts parameter for dynamic values.@include flex-center; copies mixin declarations into .card selector.@include border-radius(8px) passes argument value to mixin parameter.
