How to utilize CSS variable references across different files in React?

In my React project, I have integrated multiple variables that I would like to be able to access from other CSS files in order to maintain a unified codebase for specific UI configurations such as colors and buttons.

However, I am uncertain whether these variables should be declared within 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 can I use references such as var(--LightYellow) in a file like home.css?

Answer №1

In most scenarios, placing the variables on the :root or body element typically yields no significant difference since all visible elements are typically descendants of the body element. However, a recommended practice is to place them on the root element.

You can easily reference these variables (e.g. var(--LightBlue)) from any stylesheet without concern for the order of stylesheets, as custom properties are inherited.

Answer №2

Utilize the :root{} selector to declare universal styles.

Answer №3

:root and html both refer to the top-level element (they are essentially the same). This is where your CSS variables should be declared in order to be used globally across multiple files:

/*
  CSS variables will be accessible everywhere
*/
html {
  --LightBlue:rgb(1,147,207); 
  --MediumBlue: rgb(1, 126, 207);
}

If you visit a random website like nextjs.org and inspect the html tag, you'll notice that they define their CSS variables there.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing a feature in ReactJS that enables users to select a minimum and maximum limit for checkboxes

I have developed a unique React application that incorporates JSON values into checkbox elements. The JSON data includes both minimum and maximum required values. I successfully implemented a function to set the checkboxes' maximum value based on the ...

Tips for Removing a Subcollection from a Firestore Database Collection

I am facing an issue with deleting a single image from a list of images. Currently, the entire postImg field is being deleted instead of just a single image. I am working on finding a solution for this problem. Here is my attempted solution: const handleDe ...

What causes the disappearance of CSS styles when attempting to modify the className in react js?

I am currently working on a basic react application, and I am trying to dynamically change the name of a div element using the following code snippet - <div className={'changeTab ' + (page.login ? 'leftSide' : 'rightSide')} ...

React component not displaying dynamic content when extending from a class

Hey guys, I'm a newbie when it comes to React and I've encountered a problem with loading content fetched from an API. Usually, I use export default function About({ posts }) which works like a charm in loading my content. However, for one specif ...

Generating an assortment of specific rows by utilizing checkboxes in React JS

I'm currently dealing with a table of data where the first column consists of checkboxes. My goal is to generate an array containing the ID of each row that is selected. const [selectedRows, setSelectedRows] = useState([]); const handleCheckbox ...

I'm looking for guidance on how to merge my JavaScript and CSS files together. Can anyone provide me

As a beginner in web development, I have been looking into combining JS and CSS files. However, explanations using terms like minifies and compilers on platforms like Github and Google are still confusing to me. Here are the CSS files I have: bootstrap ...

React Native does not seem to recognize my actual device

When I try to use the adb devices command, it detects my physical phone but when I run the react-native run-android command, it opens my emulator instead. Also, whenever I use the command npx react-native run-android --deviceId=97e2bc510706, I receive an ...

React revolutionizes the way we handle line breaks in

Just starting out in the world of coding and feeling a bit overwhelmed. I have checked out MDN, WJ3 but I'm still struggling with inserting line breaks into my code. return market.outcomes.map( ({ name, price ...

The select box in CSS is optimized for Chrome but poorly displayed in Firefox

Struggling with styling the select box for both webkit and moz browsers. It looks great in Chrome, but terrible in Firefox - the default option is not vertically aligned with the select box. Can someone help me pinpoint the issue in this code? CSS: sele ...

How to remove the black border on a material-ui button

I am currently working with the material-ui datepicker and buttons. Whenever I click on the datepicker icon to select a date or any of the buttons, I notice a black border appearing. How can I remove this black border from the design? https://i.sstatic.ne ...

Is there a way to send map data using props in React?

I just want to store and pass the current props.url to the videomodal so I can show the same active video on the video modal. I can't use useState in the map. How can I pass it? Or is there any other solution? Videos.tsx ( props.url must be in the &l ...

What is the method for configuring automatic text color in CKEditor?

https://i.sstatic.net/yEM3p.png Is there a way to change the default text color of CKEditor from #333333 to #000000? I have attempted to modify the contents.css in the plugin folder: body { /* Font */ font-family: sans-serif, Arial, Verdana, "Tr ...

Using CSS to add a resize handle and implement mouse events in Chrome

While experimenting with the resize property in CSS, I encountered an issue. I have a div that contains a canvas element. .resizable { resize: both; overflow: hidden; border: 1px solid black; } div { height: 300px; wi ...

Error encountered in React MUI: Element in array is missing the required 'key' prop react/jsx-key

{ field: 'deletedAt', headerName: 'DeleteAt', type: 'actions', width: 200, editable: false, getActions: () => [<GridActionsCellItem icon={<DeleteIcon />} label="Delete" />], } ...

What is the best way to include the "onChange" function in a component that does not natively support this prop?

After finding a useful code snippet on this page to switch languages, I attempted to enhance it by incorporating material UI components for better styling. However, whenever I change the language, it redirects me back to the home page because the MenuList ...

A guide on selecting the best UI container based on API data in React using TypeScript

I have been developing a control panel that showcases various videos and posts sourced from an API. One div displays video posts with thumbnails and text, while another shows text-based posts. Below is the code for both: <div className=""> &l ...

Troubleshooting: Resolving Compilation Errors in ReactJs Sass and VS Code

I have been attempting to incorporate Sass into my ReactJS project. I followed the steps of npm install node-sass and tried importing it with the .scss extension, but unfortunately it is not working as expected. I even consulted a W3Schools Tutorial for ...

How can a variable be exported from a React component?

Is there a technique to export a variable from a React component for use in a custom hook? The code snippet is as follows:- function App() { const SignIn=()=>{ //Some code here var userId = data.info.username; //Some code h ...

Can you offer guidance on how to include a MUI icon as a React component?

I am looking to utilize a custom name for the mui-icon component in order to have more control over its function. Due to implementation requirements, I need to choose a different name from the default one assigned to the icon. // Default import import ...

Insert item at the end of the box and move all elements upwards

Hello! I'm experimenting with creating something using javascript's createElement method. My goal is to achieve an effect similar to this image: https://i.stack.imgur.com/itKUK.gif Currently, my code is functional, but the animation goes from to ...