Next.js has strong opinions about how to organize JavaScript but not CSS. How can we develop patterns that encourage best CSS practices while also following the framework’s logic? The answer is surprisingly simple — to write well-structured CSS that balances global and local styling concerns.

I have had a great experience using Next.js to manage complex front-end projects. Next.js is opinionated about how to organize JavaScript code, but it doesn’t have built-in opinions about how to organize CSS.

After working within the framework, I have found a series of organizational patterns that I believe both conform to the guiding philosophies of Next.js and exercise best CSS practices. In this article, we’ll build a website (a tea shop!) together to demonstrate these patterns.

Note: You probably will not need prior Next.js experience, although it would be good to have a basic understanding of React and to be open to learning some new CSS techniques.

Writing “Old-Fashioned” CSS 

When first looking into Next.js, we may be tempted to consider using some kind of CSS-in-JS library. Though there may be benefits depending on the project, CSS-in-JS introduces many technical considerations. It requires using a new external library, which adds to the bundle size. CSS-in-JS can also have a performance impact by causing additional renders and dependencies on the global state.

 

Furthermore, the whole point of using a library like Next.js is to statically render assets whenever possible, so it doesn’t make so much sense to write JS that needs to be run in the browser to generate CSS.

There are a couple of questions we have to consider when organizing style within Next.js:

How can we fit within the conventions/best practices of the framework?
How can we balance “global” styling concerns (fonts, colors, main layouts, and so on) with “local” ones (styles regarding individual components)?

The answer I have come up with for the first question is to simply write good ol’ fashioned CSS. Not only does Next.js support doing so with no additional setup; it also yields results that are performant and static.

To solve the second problem, I take an approach that can be summarized in four pieces:

  1. Design tokens
  2. Global styles
  3. Utility classes
  4. Component styles

I’m indebted to Andy Bell’s idea of CUBE CSS (“Composition, Utility, Block, Exception”) here. If you haven’t heard of this organizational principle before, I recommended checking out its official site or feature on the Smashing Podcast. One of the principles we will take from CUBE CSS is the idea that we should embrace rather than fear the CSS cascade. Let’s learn these techniques by applying them to a website project.

 

#next #nextjs #react #javascript #css #webdev

 

Global vs. Local Styling In Next.js
8.40 GEEK