Applying global CSS styles in a React app


Borislav Hadzhiev

Last updated: Apr 24, 2022


Photo from Unsplash

Applying global CSS styles in a React app #

To apply global CSS styles in a React app, write your css in a file with a .css extension and import it in your index.js file. Global CSS should be imported in index.js to make sure it's loaded on all pages of your React app.

Here is an example of an index.css file that declares 2 globally available classes.

.bg-salmon { background-color: salmon; } .text-white { color: white; }

And here is how we would import the index.css file in our index.js file.

// 👇️ import css import './index.css'; import {createRoot} from 'react-dom/client'; import App from './App'; const rootElement = document.getElementById('root'); const root = createRoot(rootElement); root.render( <App /> );

The example above assumes that your index.css file is located in the same directory as your index.js file.

When importing global CSS files in React, it's a best practice to import the CSS file into your index.js file.

The index.js file is the entry point of your React application, so it's always going to be ran.

On the other hand, if you import a CSS file into a component, the CSS styles might get removed once your component unmounts.

If you use CSS Modules to style your React app, you can switch to global scope for the current selector by passing it to :global.

:global(.bg-salmon) { background-color: salmon; }

If the selector is switched to global mode, it won't be modified by CSS modules and will be available in the global scope.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.