You cannot use CSS variables in media queries FIX (for styled components)

Olatade Abiona
1 min readDec 11, 2020

For sometime, I have not written extensive CSS which is my excuse for forgetting that CSS variables will not work in media queries.

Alright let’s get to the problem first and then the solution.

/* WHAT YOU WANT TO DO *//* Declaring your variables */
:root{
--mobile: 375px;
--tablet: 768px;
--laptop: 1024px;
}
/* this will not work */
@media only screen and (min-width: var(--mobileScreen) {
background-color: red;
max-width: 500px;
}

If you try this, your media query will not work. You can find a good explanation on stackoverflow.

Since you want to have a single location where you can change query widths across your CSS I found this solution very useful in my project. First I created a file where all my screen variables will reside.

/* mediaVariables.js */const ScreenSizes = {
"mobile": "375px",
"tablet": "768px",
"laptop": "1024px",
};

export default ScreenSizes;

Since your variables have been exported, you can now access them in all your styled components like I did below.

/* layout.js */import ScreenSizes from './mediaVariables';const Layout = styled.div`@media only screen and (min-width: ${ScreenSizes.mobile}{
background-color: red;
max-width: 500px;
}
`;

Now you can use variables in all your CSS across your project. Whenever you feel like changing a variable value, all you have to do is change it in mediaVariables.js.

--

--

Olatade Abiona

I am in the pursuit of happiness. I'll be fine once I get it