我可以将CSS变量与'picture-> source-> media'属性一起使用吗? [英] Can I use CSS variables with the 'picture->source->media' attribute?

查看:70
本文介绍了我可以将CSS变量与'picture-> source-> media'属性一起使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的HTML中,我有...



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



...完全符合预期。



问题是我有多个图像,即使在不同的页面上,我希望响应相同的屏幕宽度媒体查询。所以,我以为我会使用CSS变量。我改为这个...



在单独的 styles.css 文件中:



:root 
{
--image-big:1200px;
--image-small:600px;
}



在HTML文件中:



< picture> 
< 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>
< / picture>





...但它似乎不起作用。据我所知,我总是得到较小的图像。我不确定这是由第二个来源行还是后备 img 行触发。



这应该有用吗?如果是这样,任何人都可以发现我做错了什么(除了以编程为生!)



我尝试了什么:



我尝试使用比更具体的范围:root (例如将一个类分配给图片元素和目标那个)。



我也试过在Edge的开发者工具中挖掘但是看不到帮助我的任何事情。

解决方案

CSS变量只能用作CSS属性的值。它们不能在媒体查询测试中使用,这是媒体属性:

var()函数不能用作属性名称,选择器或属性值之外的任何其他内容。



CSS原生变量在媒体查询中不起作用 - Stack Overflow [ ^ ]


In my HTML, I have...

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


...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:

:root
{
	--image-big: 1200px;
	--image-small: 600px;
}


In HTML file:

<picture>
	<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">
</picture>



...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.

解决方案

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[^]


这篇关于我可以将CSS变量与'picture-&gt; source-&gt; media'属性一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆