0
0
AstroHow-ToBeginner ยท 4 min read

How to Use Sass in Astro: Simple Setup and Example

To use Sass in Astro, install sass via npm and then import .scss or .sass files directly in your Astro components or pages. Astro automatically compiles Sass files to CSS during build, so you can write Sass syntax seamlessly.
๐Ÿ“

Syntax

In Astro, you write Sass styles in files with .scss or .sass extensions. You import these files into your components or pages using the import statement. Astro compiles Sass to CSS automatically.

Example parts:

  • import './styles.scss'; - imports Sass styles.
  • .scss file - contains Sass syntax like variables, nesting, and mixins.
  • Astro component - where you use the imported styles.
astro
---
import './styles.scss';
---
<html>
  <head>
    <title>Astro Sass Example</title>
  </head>
  <body>
    <h1 class="title">Hello with Sass!</h1>
  </body>
</html>
๐Ÿ’ป

Example

This example shows how to create a Sass file with variables and nesting, import it into an Astro component, and see the styled output.

astro
// styles.scss
$primary-color: #4caf50;

.title {
  color: $primary-color;
  font-family: Arial, sans-serif;
  &:hover {
    color: darken($primary-color, 15%);
  }
}

---

---

import './styles.scss';

<html>
  <body>
    <h1 class="title">Hello with Sass!</h1>
  </body>
</html>
Output
<h1 class="title" style="color: #4caf50; font-family: Arial, sans-serif;">Hello with Sass!</h1> (hover changes color to a darker green)
โš ๏ธ

Common Pitfalls

Common mistakes when using Sass in Astro include:

  • Not installing sass package, so imports fail.
  • Using incorrect file extensions like .css instead of .scss or .sass.
  • Forgetting to import the Sass file in the component or page.
  • Trying to use Sass features inside <style> tags without proper setup.

Always run npm install -D sass before using Sass.

astro
/* Wrong: importing CSS file instead of SCSS */
import './styles.css'; // No Sass features here

/* Right: import Sass file */
import './styles.scss';
๐Ÿ“Š

Quick Reference

Summary tips for using Sass in Astro:

  • Install Sass with npm install -D sass.
  • Use .scss or .sass files for styles.
  • Import Sass files directly in Astro components or pages.
  • Write Sass syntax like variables, nesting, and mixins inside these files.
  • Astro compiles Sass automatically during build.
โœ…

Key Takeaways

Install the Sass package with npm before using Sass in Astro.
Write styles in .scss or .sass files and import them in your Astro components.
Astro automatically compiles Sass to CSS during build without extra config.
Always import your Sass files where you want the styles applied.
Use Sass features like variables and nesting inside your .scss files for cleaner styles.