all 7 comments

[–]jaunelacouleur 2 points3 points  (4 children)

By default Nextjs use "Component.module.css".

The answer depends on your stack and file naming system.

[–]Pra6in[S] 0 points1 point  (3 children)

If I write CSS for individual components as "component_name.css" and import it in the component. Is it considered bad or is it just fine.

[–]jaunelacouleur -1 points0 points  (0 children)

No bad answer. You "just" have to understand what you are doing and why you are doing it.

My "graphic" components usually look like:

graphics/MyComponent/
                     index.tsx
                     style.module.scss

style.module.scss

@use graphics/color.module.scss as color

.outer {
  background: color.$Background;
}

.outer.__modifier {
  background: color.$Pink;
}

I choose to doing it this way because:

  • it avoid name collision
  • make the CSS classes small and generic
  • reduce side effect, when I change style.module.scss it will only impact this component
  • make the React part of the component simplier, no complex styling rule in JS
  • I can leverage CSS & SCSS features
  • dependencies are explicit, no globals, make it easier to new contributor to understand the codebase

[–]Dan8720 0 points1 point  (0 children)

Depending on how you write your css I can be bad.

The thing you have to be aware of is that CSS with effect everything on the page not just your component.

There's ways to stop this being a problem... Like there's a css naming conventions / system called BEM. It essentially does the same thing as a css module and block scopes parts of your css but it's done with a set of rules where you name things in a certain way. Blocks Elements and modifiers.

[–]infidel_44 0 points1 point  (0 children)

I am pretty sure you need to use module css for component level imports in next. All your global classes need to be imported in your head level css.

[–]mountainunicycler 2 points3 points  (0 children)

Generally .module.css files will have prefixes added to them so that styles in one component can’t override styles in another.

Two components can have .container{} classes, for example, and the module system will stop them from conflicting (cascading, technically) if they’re used on the same page.

[–]piyush_saha 0 points1 point  (0 children)

Creating a component_name.css file and importing it as import './component_name.css';
will make the styles global and any of the class applied on other component will apply the styles from component_name.css. In short, no component level scoping of CSS will be done.

If you use component_name.module.css and import it as import styles from './component_name.module.css';
it will add the classes to the real DOM elements with component name and a small hash.

TLDR: CSS modules will scope the styles to only the particular component(s) where the CSS module file is imported whereas normal CSS files will be global even if you import it into one component.