fervor [>]CODING & CURIOSITY
FERVOR LEARNING SYSTEMTUTORIALS
← CSS

CSS / 2 MIN READ

Variables in CSS Modules

Explore how to use CSS variables effectively in modular stylesheets.

From the original Fervor library. Examples may use older package versions.

How to Use CSS Variables Across Multiple CSS Modules in React

CSS variables, also known as custom properties, allow you to define reusable values in your CSS code. You can use CSS variables to maintain consistent styling across your application. Here’s a tutorial on how to use CSS variables across multiple CSS modules in a React application:

Step 1: Create a global CSS file for variables

First, create a global CSS file that will store all your CSS variables. Name it something like variables.css.

:root {
  --primary-color: #3498db;
  --secondary-color: #2ecc71;
  --font-family: 'Roboto', sans-serif;
}

Step 2: Import the global CSS file in your application

To use the CSS variables defined in the variables.css file, import it into your main application file (usually index.js or App.js).

import './variables.css';

Step 3: Create CSS modules for your components

For each React component that needs styling, create a separate CSS module. Name the CSS module file after the component (e.g., MyComponent.module.css). Then, import the CSS module into your component file and use the style object.

.myComponent {
  background-color: var(--primary-color);
  font-family: var(--font-family);
}

Step 4: Use CSS variables in your CSS modules

In the CSS module, you can now use the CSS variables defined in the variables.css file using the var() function.

.myComponent {
  background-color: var(--primary-color);
  font-family: var(--font-family);
}

Step 5: Apply styles to your components

In your React component file, import the CSS module and apply the styles using the className attribute.

import React from 'react';
import styles from './MyComponent.module.css';

function MyComponent() {
  return (
    <div className={styles.myComponent}>
      My Component
    </div>
  );
}

export default MyComponent;

By following these steps, you can use CSS variables across multiple CSS modules in your React application to maintain consistent styling and make it easier to update styles in the future.

Just so you know by importing the variables.css file in the main application file, the CSS variables will be accessible in all of your ‘CSS modules’.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import './variables.css'; // Import the variables.css here

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

Now go make some code easier to maintain!!!

Keep your curiosity going.Explore more CSS →
287 TUTORIALS · 22 TOPICSREADY