Home > Blockchain >  In React how to CSS reference variables in separate files
In React how to CSS reference variables in separate files

Time:06-09

I have a react project, I have inserted a bunch of variables which I would ideally be able to reference from other CSS files to have a single code base for certain UI configuration (colours, buttons, etc.).

Though I'm unsure if it should be inside of body{} or :root{}

Index.css

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
    
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;

  margin: 0;

  min-width: 100%;
  min-height: 100%;
  margin: 0;
  padding: 0;

  background-repeat: no-repeat;
  background: var(--GradientLighterBlue);

  --LightBlue:rgb(1,147,207); 
  --MediumBlue: rgb(1, 126, 207);
  --DarkBlue: rgb(7, 101, 195);
  --GradientLighterBlue: linear-gradient(0deg, rgba(1,126,207,1) 0%, rgba(1,147,207,1) 100%);
  --GradientDarkerBlue: linear-gradient(0deg, rgba(7,101,195,1) 0%, rgba(0,72,144,1) 100%);


  --LightYellow: rgb(252,177,52);
  --MediumYellow: rgb(194,136,41);
  --GradientYellow: linear-gradient(0deg, rgba(194,136,41,1) 0%, rgba(252,177,52,1) 100%);
}

How do I reference these eg. var(--LightYellow) in for example home.css ?

CodePudding user response:

In most cases there is no practical difference between putting the variables on the :root element or on the body element, since all visible elements should be descendants of the body element, but it's a good practice to put the on the root element.

You can reference the variables normally (i.e. var(--LightBlue)) from any other stylesheet, regardless of the order of the stylesheets, because custom properties are inherited.

CodePudding user response:

:root and html are reference to the top-level element (they're same). So your css-variables should be there in order to use globally across files:

/*
  css-variable will be available everywhere
*/
html {
  --LightBlue:rgb(1,147,207); 
  --MediumBlue: rgb(1, 126, 207);
}

If you open random website for example nextjs.org and inspect the html tag you will the they put their css-variables there.

CodePudding user response:

use :root{} for declare global uses.

  • Related