Component-Scoped Styles with CSS Modules
Component-scoped CSS allows you to write traditional, portable CSS with minimal side effects: gone are the worries of selector name collisions or affecting other components’ styles.
Quoting from the CSS Module homepage:
A CSS Module is a CSS file in which all class names and animation names are scoped locally by default.
The CSS in a CSS module is no different than normal CSS, but the extension of the file is different to mark that the file will be processed.
containerStyles. Then, a CSS class from that object is referenced in the JSX
className attribute with
containerStyles.container, which renders into HTML with dynamic CSS class names like
Adding a persistent CSS
className to your JSX markup along with your CSS Modules code can make it easier for users to take advantage of User Stylesheets for accessibility.
Here’s an example where the class name
container is added to the DOM along with the module’s dynamically-created class names:
A site user could then write their own CSS styles matching HTML elements with a class name of
.container, and it wouldn’t be affected if the CSS module name or path changed.
CSS Modules are highly recommended for those new to building with Gatsby (and React in general) as they allow you to write regular, portable CSS files while gaining performance benefits like only bundling referenced code.
Visit the CSS Modules section of the tutorial for a guided tour of building a page with CSS Modules.