Sass Mixins

Sass Tutorial

Sass Mixins

Sass Mixins let you create reusable blocks of CSS that you can include anywhere in your stylesheet.
They are perfect for avoiding repetition and handling vendor prefixes, reusable layouts, and patterns.


 Basic Mixin Syntax

Define a Mixin

@mixin center {
display: flex;
justify-content: center;
align-items: center;
}

Use a Mixin

.box {
@include center;
}

 Mixin with Parameters

@mixin border-radius($radius) {
border-radius: $radius;
}
.card {
@include border-radius(10px);
}


Mixin with Multiple Parameters

@mixin button-style($bg, $color, $padding) {
background: $bg;
color: $color;
padding: $padding;
}
.btn-primary {
@include button-style(blue, white, 10px 20px);
}


 Default Parameter Values

@mixin shadow($x: 0, $y: 2px, $blur: 5px, $color: #000) {
box-shadow: $x $y $blur $color;
}
.card {
@include shadow;
}


 Mixins with Content (@content)

Used to pass custom styles inside a mixin.

@mixin responsive {
@media (max-width: 768px) {
@content;
}
}
.container {
width: 100%;

@include responsive {
width: 90%;
}
}


Mixin for Vendor Prefixes

@mixin transform($value) {
-webkit-transform: $value;
-ms-transform: $value;
transform: $value;
}
.box {
@include transform(rotate(45deg));
}


 Real-Life Example (Button Mixin)

@mixin button($bg-color) {
background-color: $bg-color;
color: white;
padding: 10px 20px;
border-radius: 5px;
}
.btn-success {
@include button(green);
}

.btn-danger {
@include button(red);
}


 Mixin vs Extend (@extend)

Mixins Extend
Copies CSS code Shares CSS rules
Supports parameters No parameters
More flexible Less flexible

✅ Best Practices

✔ Use mixins for reusable patterns
✔ Avoid large mixins everywhere (CSS bloat)
✔ Use parameters wisely
✔ Prefer mixins for vendor prefixes


📌 Summary

  • Mixins are reusable CSS blocks

  • Use @mixin to define

  • Use @include to apply

  • Supports parameters & media queries

You may also like...