Applying global CSS styles in a React app

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
2 min

banner

# 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.

index.css
.bg-salmon { background-color: salmon; } .text-white { color: white; }
The code for this article is available on GitHub

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

index.js
// 👇️ 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 run.

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

You can apply the global styles in any of your files.

Here is an example App component that makes use of the two classes.

App.js
const App = () => { return ( <div> <div className="bg-salmon text-white">bobbyhadz.com</div> </div> ); }; export default App;

global styles applied

The code for this article is available on GitHub

# Applying global CSS styles in a React app with CSS Modules

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.

index.css
: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.