Sass — Mixins
Basic mixin
@mixin flex-center {
display: flex;
justify-content: center;
align-items: center;
}
.container {
@include flex-center;
}
Mixin with parameters
@mixin button($bg: #3498db, $text: white, $padding: 10px 20px) {
background: $bg;
color: $text;
padding: $padding;
border: none;
border-radius: 4px;
cursor: pointer;
}
.btn-primary {
@include button(#3498db);
}
.btn-secondary {
@include button(#2ecc71);
}
Responsive mixins
@mixin respond($breakpoint) {
@if $breakpoint == 'mobile' {
@media (max-width: 480px) { @content; }
} @else if $breakpoint == 'tablet' {
@media (max-width: 768px) { @content; }
} @else if $breakpoint == 'desktop' {
@media (max-width: 1024px) { @content; }
}
}
.container {
width: 100%;
@include respond('tablet') {
width: 75%;
}
@include respond('mobile') {
width: 100%;
}
}
Positioning mixin
@mixin position($top: null, $right: null, $bottom: null, $left: null) {
position: absolute;
top: $top;
right: $right;
bottom: $bottom;
left: $left;
}
.overlay {
@include position(0, 0, 0, 0);
}
Text utilities
@mixin truncate($lines: 1) {
@if $lines == 1 {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
} @else {
display: -webkit-box;
-webkit-line-clamp: $lines;
-webkit-box-orient: vertical;
overflow: hidden;
}
}
.truncate-1 { @include truncate(1); }
.truncate-3 { @include truncate(3); }
Transition mixin
@mixin transition($props: all, $duration: 0.3s, $easing: ease) {
transition: $props $duration $easing;
}
.button {
@include transition(background);
background: #3498db;
&:hover {
background: #2980b9;
}
}
Content directive
@mixin apply-to($selector) {
#{$selector} {
@content;
}
}
@include apply-to('.card') {
background: white;
border-radius: 8px;
}
Mini Practice
- Build a button mixin with color variants
- Create a responsive breakpoint mixin
- Make a typography mixin for headings
- Create a grid mixin using @content
Up Next
Continue with Extend — sharing styles between selectors.
Related Topics
Frequently Asked Questions about Mixins
What is Mixins in Sass?
Mixins is a fundamental concept in Sass. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Mixins?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Mixins.
Why is Mixins important in Sass?
Mixins is essential for Sass development. Understanding this concept will help you write better code and solve real-world problems more effectively.