0
0
SASSmarkup~5 mins

Why mixins eliminate duplication in SASS

Choose your learning style9 modes available
Introduction

Mixins help you write code once and use it many times. This stops you from repeating the same styles over and over.

When you want to reuse a group of CSS styles in different places.
When you need to keep your styles consistent across your website.
When you want to save time by not writing the same code multiple times.
When you want to make your CSS easier to update later.
When you want to add optional style parts with parameters.
Syntax
SASS
@mixin mixin-name($param1, $param2) {
  // styles here
}

@include mixin-name(value1, value2);

Use @mixin to define reusable styles.

Use @include to add those styles where you want.

Examples
This mixin centers content using flexbox. We use it inside .box to avoid repeating the flex styles.
SASS
@mixin center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  @include center;
  height: 100px;
  width: 100px;
  background: lightblue;
}
This mixin takes a color parameter to style different buttons with the same shape but different colors.
SASS
@mixin button-style($color) {
  background-color: $color;
  border: none;
  padding: 0.5rem 1rem;
  color: white;
  border-radius: 0.25rem;
}

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

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

This example shows a box with text centered both horizontally and vertically. The centering styles come from a mixin in SASS, which avoids repeating the flexbox code.

SASS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Mixin Example</title>
  <style>
    /* Compiled CSS from SASS */
    .box {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100px;
      width: 100px;
      background: lightblue;
      margin: 1rem;
      font-family: Arial, sans-serif;
    }
  </style>
</head>
<body>
  <div class="box">Centered Text</div>
</body>
</html>
OutputSuccess
Important Notes

Mixins make your CSS DRY (Don't Repeat Yourself).

You can add parameters to mixins to make them flexible.

Using mixins helps keep your styles consistent and easy to update.

Summary

Mixins let you write styles once and reuse them everywhere.

They stop you from copying and pasting the same code.

Mixins can take inputs to customize styles for different uses.