Ask Your Question
4

How to utilize CSS-modules variables within Javascript?

asked 2023-07-15 12:33:49 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-15 12:42:02 +0000

lakamha gravatar image

CSS-modules are a great way to organize and modularize CSS, and they can also be used to define variables. Here's how you can utilize these variables within JavaScript:

  1. Declare your CSS variables in a .css file with the :root selector:
:root {
  --primary-color: blue;
  --secondary-color: red;
  --font-size: 16px;
}
  1. Import your CSS file into your JS module using import statement:
import styles from './styles.css'; // import CSS-modules

Note: It's important to ensure your CSS file is imported with a .css extension, and that you have set up webpack to handle these imports.

  1. Access your CSS variables from the styles object:
console.log(styles['--primary-color']); 
console.log(styles['--secondary-color']); 
console.log(styles['--font-size']);

This will print the value of the CSS variables onto the console.

  1. Use your CSS variables in your JS module:
document.body.style.backgroundColor = styles['--primary-color'];

This will set the background color of the <body> element to the value of the --primary-color variable.

That's it! You can now use your CSS-modules variables directly in your JavaScript, making your code more maintainable and organized.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-15 12:33:49 +0000

Seen: 10 times

Last updated: Jul 15 '23