Skip to content

Using SCSS modules in Astro

Published:

Let's go through how you can use SCSS and CSS modules on your Astro.js project in less than 1 minute!

Using a SCSS module

To begin, you need to add SCSS support to your project by installing the SASS package. Run this on your project's terminal: npm i sass. No need to do any additional configuration.

To use a SCSS module in Astro, you first need to create the actual SCSS file with file name ending with .module.scss like this:

Screenshot of a SCSS module file being next to its component file

Then, you import it to your component or page file like this:

import CSS from './Hero.module.scss';

Your SCSS file works the usual way, you don't have to do anything additional there.

To use a SCSS module class in your HTML, add it like this:

import CSS from './Hero.module.scss';
---
<section class={CSS.hero}>
<h1>Hello world</h>
</section>

The class has now been applied. Let's see what the class on the actual Astro site now looks like:

The 'hero' class has now randomly generated letters on it

As you can see, the hero class got some randomized letters and numbers to it. This makes it possible to use the "hero" class in other components too, as they will have their own unique numbers and letters, making sure that the class names are unique on each component.

Combining a SCSS module class with a global class

If you want to combine the SCSS module class with a regular global class, do this:

import CSS from './Hero.module.scss';
---
<section class={`hero-global-class ${CSS.hero}`}>
<h1>Hello world</h>
</section>

That results in the "hero-global-class" being non-randomly generated, in other words, just a regular class.

Using multiple SCSS module classes on an element

If you want to have more than one SCSS module class on an element, you can do it the same way as adding additional global classes:

import CSS from './Hero.module.scss';
---
<section class={`${CSS.hero} ${CSS.secondClass}`}>
<h1>Hello world</h>
</section>