Recently, I transitioned to next.js and I'm eager to develop an application with CSS styles without resorting to css-in-js or inline styling. In my exploration, I've come across two potential options: using CSS modules or importing global styles in _app.js. The distinction between the two can be summarized as follows:
- CSS modules are loaded only when the components utilizing them are loaded, thereby maintaining local scope.
- Global styles, on the other hand, are loaded all at once and lack a local scope.
Initially, I considered employing CSS modules due to their ability to load styles selectively based on necessity. However, I encountered challenges related to overriding styles and dealing with specificity issues. As an illustration, consider a Button component that contains an icon. While the default state of this Button includes certain stylings, a navigation Button might require a slightly altered appearance with a different icon size. In the case of global styles, one could use the following structure:
<div class="navigation">
<button class="navigation__button button button--modifier">
<img class="button__icon" />
<span class="button__text">Click me!</span>
</button>
</div>
...where button, button--modifier, button__icon, and button__text represent class names for the default styles of the Button component. Meanwhile, navigation__button is utilized to adjust the button specifically for navigation, potentially leveraging inheritance to modify the icon's style:
.navigation__button .button__icon {
width: 24px;
}
However, when working with CSS modules, it becomes challenging to override styles if they are defined in another .module.css file (such as Navigation.module.css). Overcoming this obstacle may require tactics like implementing the :global selector or adding specificity through alternative means, leading to increased complexity and potential conflicts.
How do developers typically navigate these challenges when utilizing CSS modules? Is there a way to separate stylesheets without relying on CSS modules or css-in-js?
Edit: Are there significant performance or loading speed discrepancies between bundling all stylesheets together, as seen with global styles, versus loading modules within components?