1

I want to have a file just to store the colors and some other settings that I am going to use in my css styles. Because I don't want to specify the same color in different files multiple times. How can I achieve that with css modules?

For example: setting.css

$primary-color: #785372;
$secondary-corlor: #22b390;

Button/styles.css

.button {
  background: $primary-color;
  display: flex;
}

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. I will check it out.
import it into your App.scss file (i bet you have that one)
CSS modules are processed per file, and not from a root file importing all the partials like Sass does. So this won't work. The partial with variables needs to be imported in each module file (if needed).
0

You can do this with using CSS Custom Properties (here's a tutorial I've found).

In your settings.css file, do (the `:root':

:root {
    --primary-color: #785372;
    --secondary-corlor: #22b390;
}

Then, you can use those constants in the same, or a different file

.container {
    color: var(--primary-color);
}

If you're using them in a different file, be sure to import both stylesheets, for example:

import './Button/styles.css'
import './settings.css'

Also, according to this answer, you can do this in html as well, by linking the two stylesheets:

<link href="settings.css" rel="stylesheet">
<link href="Button/style.css" rel="stylesheet">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.