0
0
SASSmarkup~5 mins

Reducing compiled CSS size in SASS

Choose your learning style9 modes available
Introduction

Reducing compiled CSS size helps your website load faster and saves data for visitors.

When your website feels slow to load because of large CSS files.
When you want to improve user experience on mobile devices with limited data.
When you want to keep your styles organized but avoid repeating code.
When you want to make your CSS easier to maintain without extra bulk.
When you want to reduce server bandwidth and hosting costs.
Syntax
SASS
// Use variables, mixins, and nesting carefully
$primary-color: #3498db;

@mixin button-style {
  padding: 0.5rem 1rem;
  border-radius: 0.25rem;
  background-color: $primary-color;
  color: white;
}

.button {
  @include button-style;
  font-weight: bold;
}

// Avoid deep nesting and duplicate styles

Use variables and mixins to reuse styles instead of repeating them.

Keep nesting shallow to avoid generating too many CSS rules.

Examples
Using a variable for color helps reuse and change it easily.
SASS
$color: #e74c3c;

.alert {
  color: $color;
  font-weight: bold;
}
Mixins let you group styles and include them where needed.
SASS
@mixin card-style {
  padding: 1rem;
  border: 1px solid #ccc;
  border-radius: 0.5rem;
}

.card {
  @include card-style;
  background-color: white;
}
Use shallow nesting to avoid creating too many CSS selectors.
SASS
.nav {
  display: flex;
  > li {
    margin-right: 1rem;
  }
}
Sample Program

This example uses a mixin and a variable to keep the button styles reusable and small. The compiled CSS will be shorter and easier to maintain.

SASS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Reduce CSS Size Example</title>
  <style>
    body {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
      margin: 0;
    }

    .btn {
      padding: 0.75rem 1.5rem;
      border-radius: 0.3rem;
      background-color: #2ecc71;
      color: white;
      border: none;
      cursor: pointer;
      font-size: 1rem;
      font-weight: 600;
    }
  </style>
</head>
<body>
  <button class="btn">Click Me</button>
</body>
</html>
OutputSuccess
Important Notes

Always check your compiled CSS file size after changes to see if it got smaller.

Use tools like browser DevTools to inspect which CSS rules are applied and remove unused styles.

Try to avoid repeating the same styles in different places; use variables and mixins instead.

Summary

Use variables and mixins to reuse styles and reduce repetition.

Keep nesting shallow to avoid creating many CSS selectors.

Smaller CSS files help your website load faster and improve user experience.