Last updated: Apr 7, 2024
Reading time·2 min
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.
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.
const App = () => { return ( <div> <div className="bg-salmon text-white">bobbyhadz.com</div> </div> ); }; export default App;
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.