0
0
AstroHow-ToBeginner ยท 4 min read

How to Use CSS Modules in Astro for Scoped Styling

In Astro, you can use CSS Modules by importing a .module.css file into your component and applying the imported class names to your elements. This keeps styles scoped locally to the component, avoiding global conflicts.
๐Ÿ“

Syntax

To use CSS Modules in Astro, create a CSS file with the .module.css extension. Import it in your Astro component using import styles from './filename.module.css';. Then, apply styles using class={styles.className} on your HTML elements.

This syntax ensures styles are scoped only to that component, preventing clashes with other styles.

astro
---
import styles from './Button.module.css';
---

<button class={styles.primaryButton}>Click me</button>
๐Ÿ’ป

Example

This example shows a simple Astro component using a CSS Module to style a button with a blue background and white text. The styles apply only to this button, not globally.

astro
---
import styles from './Button.module.css';
---

<button class={styles.primaryButton}>Click me</button>

/* Button.module.css */
.primaryButton {
  background-color: #007acc;
  color: white;
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.primaryButton:hover {
  background-color: #005fa3;
}
Output
A blue button with white text labeled 'Click me' that changes to a darker blue on hover.
โš ๏ธ

Common Pitfalls

  • Forgetting to use the .module.css extension will cause styles to be global, not scoped.
  • Not importing the CSS Module or using incorrect import syntax will cause errors or no styles applied.
  • Trying to use string class names instead of styles.className will not apply scoped styles.
astro
---
/* Wrong: global CSS file imported as module */
import styles from './styles.css'; // No .module.css extension

<button class={styles.primaryButton}>Click me</button>

---
/* Right: use .module.css and import */
import styles from './styles.module.css';

<button class={styles.primaryButton}>Click me</button>
๐Ÿ“Š

Quick Reference

Remember these key points when using CSS Modules in Astro:

  • Use .module.css extension for CSS files.
  • Import styles with import styles from './file.module.css';.
  • Apply classes with class={styles.className}.
  • Styles are scoped locally to the component.
โœ…

Key Takeaways

Always name your CSS files with the .module.css extension to enable CSS Modules in Astro.
Import CSS Modules using ES module syntax and apply classes via the imported object.
CSS Modules scope styles locally, preventing global style conflicts.
Avoid using plain string class names when using CSS Modules; always use the imported styles object.
Check your import paths and file extensions carefully to avoid common mistakes.