How to Apply Global Styles with CSS Modules in a React App

How to apply global styles with CSS modules in a react app?

Since you're using the ES6 import syntax you may use the same syntax to import your stylesheet

import './App.css'

Also, you can wrap your class with :global to switch to the global scope (this mean CSS Module won't modulify it, eg: adding a random id next to it)

:global(.myclass) {
background-color: red;
}

How to override global CSS in a CSS module file?

Since .flex refers to a global class you'll need to use the :global selector to target it in your CSS module.

/* Layout.module.css */

.navbar :global(.flex) {
justify-content: space-between;
}

Or using an alternate syntax.

.navbar {
:global {
.flex {
justify-content: space-between;
}
}
}

How to create a global settings file in react css modules

From your samples that looks like Sass (which can be used in conjunction with CSS modules). If so then just import the partial containing the variables.

@import 'path/to/variables.scss';

If there's no Sass involved then postcss-modules-values is what your looking for:

variables.css

@value primary: #785372;
@value secondary: #22b390;

styles.css

@value primary, secondary from './path/to/variables.css';

.button {
background: primary;
display: flex;
}

EDIT:

Actually there's even more options, still through PostCSS plugins. postcss-simple-vars or postcss-custom-properties, the later having the clear advantage to stay close to the CSS specification.
They all share the same requirement though, importing the configuration file in a way or another.

Global SCSS using CSS Modules in React (Gatsby)

You have multiple approaches. I think the best and straightforward approach is importing the partial files (variables, functions, mixins, etc) into each individual module when needed since it would be a dependency of that specific file (it makes structural sense).

If your system and modules are properly structured, webpack will tree shake your SCSS modules and will remove the dead-code so you don't need to worry about importing the same file (let's say _variables.module.scss) into each specific module.

React global SCSS: class styling not working

Are you using css-modules?

In that case, css-modules adds a hash at the end of the class name. You can avoid it by switching to the global scope for your class.

:global {
.marginsContainer {
width: 90%;
margin: auto;
padding: 100px;
}
}

A better solution is to use the class name with the hash, by importing the stylesheet like this.

import styles from '../global-styles/main.scss';

And setting the class name like this.

<div className={styles.marginsContainer}>


Related Topics



Leave a reply



Submit