How to Create Reusable Styles Using Mixins in SCSS

Creating reusable styles using mixins in SCSS helps you avoid repeating the same code across multiple components. By defining a mixin with @mixin, you can group common styles like buttons, flex layouts, or typography and reuse them using @include. Mixins can also accept parameters, allowing you to customize values such as colors, sizes, or spacing for different use cases. This makes your styles more flexible, consistent, and easier to maintain. Overall, mixins help streamline your workflow and build scalable CSS efficiently.

Why Use Mixins for Reusability

Mixins help you reuse the same group of styles across multiple components. Instead of repeating CSS, you define it once and include it wherever needed.

Example:

@mixin card-style {
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 10px rgba(0,0,0,0.1);
}

.card {
@include card-style;
}

.profile-card {
@include card-style;
}

Creating Flexible Mixins with Parameters

You can make your mixins dynamic by passing values like colors, spacing, or sizes.

Example:

@mixin button($bg, $color) {
background: $bg;
color: $color;
padding: 10px 20px;
border-radius: 5px;
}

.btn-primary {
@include button(blue, white);
}

.btn-secondary {
@include button(gray, white);
}

Using Default Values for Consistency

Default parameters allow you to maintain consistency while still having flexibility when needed.

Example:

@mixin box($padding: 15px, $radius: 8px) {
padding: $padding;
border-radius: $radius;
}

.card {
@include box; // default values
}

.large-box {
@include box(30px, 12px);
}

Reusable Layout Mixins (Flex/Grid)

Mixins are perfect for layout patterns like centering or alignment, which are used frequently in UI design.

Example:

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

.container {
@include flex-center;
height: 100vh;
}

Advanced Reusability with @content

Using @content, you can pass custom styles into a mixin, making it extremely reusable and powerful.

Example:

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

.box {
width: 400px;

@include responsive {
width: 100%;
}
}