author avatar

vaibhav.yadav

Sat Jun 01 2024

Recently I came across an interesting use case of combining CSS variables with environment variables. The challenge was to change a CSS property, particularly a color, based on an environment variable. Since CSS doesn't support environment variables directly, here's the approach I took:

The global css file:


:root {
  /* ----- fallback value ----- */
  --primary-color: #3498db;
}

h1 {
  color: var(--primary-color);
}


Then, in our React application:


const App = () => {
  const primaryColor = process.env.NAME === 'a' ? '#fff' : '#000';

  return (
    <div style={{ '--primary-color': primaryColor }}>
      <h1>Hello, World!</h1>
    </div>
  );
};


#css #cssvariables #react