CodexBloom - Programming Q&A Platform

CSS Variables implementation guide in Responsive Design with Media Queries in React

πŸ‘€ Views: 79 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-25
css react styled-components JavaScript

I'm prototyping a solution and After trying multiple solutions online, I still can't figure this out... I'm working with an scenario with CSS variables in my React project that uses styled-components. I have a set of CSS variables for theme colors that I want to adjust based on media queries for better responsiveness. However, the variables do not seem to update when the viewport changes size. Here’s a simplified version of what I’ve attempted: ```javascript import styled from 'styled-components'; const Container = styled.div` --primary-color: blue; background-color: var(--primary-color); height: 100vh; @media (max-width: 600px) { --primary-color: red; } `; function App() { return <Container />; } ``` In this example, I expect the background color to change from blue to red when the screen width is less than 600px. However, it remains blue regardless of the viewport size. I’ve checked the browser compatibility and I know that CSS variables are supported in the latest versions of most browsers, including Chrome and Firefox. I've also tried placing the media query directly in the global styles but that didn't resolve the scenario either. I even attempted to debug using the browser's developer tools, but the `--primary-color` variable appears unchanged when I resize the window. Is there a specific way to correctly implement CSS variables with media queries in React? Any insights or suggestions would be greatly appreciated! For context: I'm using Javascript on macOS.