If you add the root css variables in index.css
you can access these globally without using @import
This is assuming that index.css
is imported in the src/App.js
file as the default file structure.
css modules are scoped meaning that the variables inside them are local, but that does not mean you cannot access variables from a global css file.
Example One
Let's say this is our index.css
:root {
--header-width: 95vw;
--border-radius-one: 5px;
}
body {
background-color: #261d54;
margin: 0;
font-family: "Poppins", sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
We can then access this root css variables like so:
#header {
margin: 0 auto;
width: var(--header-width);
border:1px solid blue;
border-radius: var(--border-radius-one);
}
Now, if you would like to modify these variables from the script, so that you can make them dynamic you can use the setProperty() JS method to set a new value for a CSS property.
So, the way you would do this in React is by creating a function to change the property and implement an onClick
in JSX
Example Two
function changeFontSize(size){
document.documentElement.setProperty('--font-size', size)
}
return(
<div>
<button onClick={() => changeFontSize('18px')}>
set font size to 18px
</button>
<button onClick={() => changeFontSize('12px')}>
set font size to 12px
</button>
</div>
)
If you want to read about documentElement go here.
@Value
syntax mentioned. – Marlinmarline