CSS Modules help keep styles organized and avoid conflicts by making CSS local to components.
0
0
CSS Modules support in Astro
Introduction
When you want to style components without affecting other parts of the page.
When working on a project with many developers to prevent style clashes.
When you want to write CSS that is easier to maintain and debug.
When building reusable components that need their own styles.
When you want to use scoped CSS in Astro components.
Syntax
Astro
import styles from './Component.module.css'; --- <div class={styles.className}>Content</div>
Import the CSS file as a module using import styles from './file.module.css'.
Use the imported styles object to apply class names with class={styles.className}.
Examples
This example shows how to apply a local CSS class
primary to a button.Astro
import styles from './Button.module.css'; --- <button class={styles.primary}>Click me</button>
Multiple classes from the CSS module can be used on different elements inside the component.
Astro
import styles from './Card.module.css'; --- <section class={styles.card}> <h2 class={styles.title}>Title</h2> </section>
You can combine multiple CSS module classes by joining them in a string.
Astro
import styles from './Alert.module.css'; --- <div class={`${styles.alert} ${styles.warning}`}>Warning message</div>
Sample Program
This Astro component imports a CSS module and applies local styles to a message box and its text.
Astro
import styles from './Message.module.css'; --- <div class={styles.message}> <p class={styles.text}>Hello from CSS Modules!</p> </div>
OutputSuccess
Important Notes
CSS Modules automatically generate unique class names to avoid conflicts.
Use the .module.css file extension to enable CSS Modules in Astro.
Inspect the rendered HTML in browser DevTools to see the generated unique class names.
Summary
CSS Modules keep styles local to components, preventing conflicts.
Import CSS files as modules and use the imported object to apply classes.
Combine multiple classes by joining them in a string if needed.