是否可以将CSS @media规则嵌入? [英] Is it possible to put CSS @media rules inline?

查看:87
本文介绍了是否可以将CSS @media规则嵌入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将横幅图片动态加载到HTML5应用中,并且需要几个不同的版本以适应屏幕宽度。我无法正确确定手机的屏幕宽度,因此,我可以想到这样做的唯一方法是添加一个div的背景图片,并使用@media确定屏幕宽度并显示正确的图片。



例如:

 < span style =background-image:particular_ad.png; @media(max-width:300px){background-image:particular_ad_small.png;}>< / span>这是可能的,还是有任何其他建议?

div,

不, @media 规则和媒体查询不能存在于内联样式属性中,因为它们只能包含 property:value 声明。如规范所示:



< blockquote>

style属性的值必须与CSS的内容的语法相匹配声明块


将样式应用于特定媒体的元素的唯一方法是使用单独的规则



一个虚拟 span 在你的样式表中,你需要提供一个选择器。选择器看起来像这样,但如果你定位一个非常具体的元素,你需要一个更具体的选择器:

  span { background-image:url(particular_ad.png); } 

@media(max-width:300px){
span {background-image:url(particular_ad_small.png); }
}


I need to dynamically load banner images into a HTML5 app and would like a couple of different versions to suit the screen widths. I can't correctly determine the phone's screen width, so the only way I can think of doing this is to add background images of a div and use @media to determine the screen width and display the correct image.

For example:

 <span style="background-image:particular_ad.png; @media (max-width:300px){background-image:particular_ad_small.png;}"></span>

Is this possible, or does anyone have any other suggestions?

解决方案

No, @media rules and media queries cannot exist in inline style attributes as they can only contain property: value declarations. As the spec puts it:

The value of the style attribute must match the syntax of the contents of a CSS declaration block

The only way to apply styles to an element only in certain media is with a separate rule in your stylesheet, which means you'll need to come up with a selector for it.

A dummy span selector would look like this, but if you're targeting a very specific element you will need a more specific selector:

span { background-image: url(particular_ad.png); }

@media (max-width: 300px) {
    span { background-image: url(particular_ad_small.png); }
}

这篇关于是否可以将CSS @media规则嵌入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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