0
0
RemixHow-ToBeginner ยท 3 min read

How to Use CSS Modules in Remix for Scoped Styling

In Remix, you can use CSS Modules by importing a CSS file with the .module.css extension into your component and applying the styles as an object. This keeps styles scoped locally to the component, avoiding global conflicts.
๐Ÿ“

Syntax

To use CSS Modules in Remix, create a CSS file with the .module.css extension. Import it into your component as an object. Use the object's keys as class names in your JSX.

  • import styles from './styles.module.css': imports CSS classes as an object.
  • className={styles.className}: applies the scoped CSS class.
jsx
import styles from './Button.module.css';

export default function Button() {
  return <button className={styles.primary}>Click me</button>;
}
Output
A button with styles scoped from Button.module.css applied.
๐Ÿ’ป

Example

This example shows a Remix component using a CSS Module to style a button with a blue background and white text. The styles are scoped only to this button.

jsx
/* Button.module.css */
.primary {
  background-color: #0070f3;
  color: white;
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 0.25rem;
  cursor: pointer;
}

// Button.jsx
import styles from './Button.module.css';

export default function Button() {
  return <button className={styles.primary}>Click me</button>;
}
Output
A blue button labeled 'Click me' with white text and rounded corners.
โš ๏ธ

Common Pitfalls

Common mistakes when using CSS Modules in Remix include:

  • Not naming the CSS file with .module.css extension, which disables module scoping.
  • Trying to use global class names without :global syntax inside the module.
  • Forgetting to import the CSS module or importing it incorrectly.
  • Using string class names instead of referencing the imported styles object.

Always ensure your CSS file ends with .module.css and you use the imported object for class names.

jsx
/* Wrong way: styles.css without .module.css */
import styles from './styles.css'; // This will not work as CSS Module

/* Right way: */
import styles from './styles.module.css';
๐Ÿ“Š

Quick Reference

Remember these key points when using CSS Modules in Remix:

  • File must be named *.module.css.
  • Import styles as an object: import styles from './file.module.css'.
  • Use styles with className={styles.className}.
  • Use :global inside CSS module for global styles.
โœ…

Key Takeaways

Name your CSS files with the .module.css extension to enable CSS Modules in Remix.
Import CSS Modules as objects and use their keys as class names in JSX.
CSS Modules scope styles locally, preventing global style conflicts.
Use :global inside CSS Modules for any styles that must be global.
Always verify your import paths and file extensions to avoid errors.