Click here to Skip to main content
15,307,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my HTML, I have...

	<source media="(min-width: 1200px)" srcset="images/Size600.jpg">
	<source media="(min-width: 600px)" srcset="images/Size300.jpg">
	<img src="images/Size300.jpg">

...which works exactly as expected.

The problem is that I have multiple images, even on different pages, that I wish to respond to the same screen-width media query. So, I thought I'd use CSS variables. I changed to this...

In a separate styles.css file:

	--image-big: 1200px;
	--image-small: 600px;

In HTML file:

	<source media="(min-width: val(--image-big))" srcset="images/Size600.jpg">
	<source media="(min-width: val(--image-small))" srcset="images/Size300.jpg">
	<img src="images/Size300.jpg">

...but it doesn't seem to work. As far as I can tell, I always get the smaller image. I'm not sure if this is being triggered by the second source line or the fallback img line.

Should this work? If so, can anyone spot what I'm doing wrong (apart from programming as a living!)?

What I have tried:

I've tried using a more specific scope than :root (e.g. assigning a class to the picture element and targeting that).

I've also tried digging around in Edge's developer tools but can't see anything that helps me.
Updated 14-May-19 5:12am

1 solution

CSS variables can only be used as a value of a CSS property. They cannot be used within a media query test, which is what the media attribute is:
The var() function can not be used as property names, selectors, or anything else besides property values.

CSS native variables not working in media queries - Stack Overflow[^]
Patrick Skelton 15-May-19 3:40am
I see. At least I now understand why it doesn't work. Still, it seems like a maintenance problem to me. My understanding of CSS variables is that avoidance of repeated constants is precisely the problem they were intended to solve. Guess I can get round it when I convert my current static HTML/CSS site to MVC/C# but I would like to see one of the proposed solutions in the GitHub thread on SO implemented.

Thank you for the answer, Richard.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900