Using SCSS mixins allows you to create reusable blocks of styles that can be included anywhere in your stylesheet. You can define a mixin using @mixin and reuse it with @include, helping to avoid repeating code. Mixins can also accept parameters, making them flexible for different use cases like buttons, layouts, or responsive designs. This improves consistency and keeps your styles more organized and maintainable. Overall, SCSS mixins make your CSS more dynamic and efficient.
What is a Mixin in SCSS?
A mixin allows you to reuse a group of CSS properties across multiple elements. It helps avoid repetition and keeps your code DRY (Don’t Repeat Yourself).
Example:
@mixin box-style {
padding: 20px;
border-radius: 8px;
background: #f5f5f5;
}
.card {
@include box-style;
}
Creating a Basic Mixin
You define a mixin using @mixin and reuse it with @include wherever needed.
Example:
@mixin center {
display: flex;
justify-content: center;
align-items: center;
}
.container {
@include center;
}
Using Parameters in Mixins
Mixins can accept parameters, allowing you to pass dynamic values for more flexibility.
Example:
@mixin button($bg-color) {
background: $bg-color;
color: white;
padding: 10px 20px;
}
.btn-primary {
@include button(blue);
}
.btn-danger {
@include button(red);
}
Default Values in Mixins
You can set default values for parameters so they work even if no value is passed.
Example:
@mixin box($padding: 10px) {
padding: $padding;
border: 1px solid #ccc;
}
.card {
@include box; // uses default
}
.box-large {
@include box(20px);
}
Advanced Mixins (Responsive Example)
Mixins are very useful for responsive design and reusable patterns like media queries.
Example:
@mixin responsive($breakpoint) {
@if $breakpoint == mobile {
@media (max-width: 768px) {
@content;
}
}
}
.container {
width: 1200px;
@include responsive(mobile) {
width: 100%;
}
}



