Html 我可以在内部 CSS 中使用媒体查询,它会避免加载我定义的背景图像吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12906913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I use a media query in internal CSS, and will it avoid loading the background images I define?
提问by GusRuss89
I'm working on a responsive site where each page will have a large hero image, defined in the CMS. I'd like to avoid having to download that background image on mobiles.
我正在开发一个响应式网站,其中每个页面都有一个大的英雄图像,在 CMS 中定义。我想避免在手机上下载该背景图片。
The only way I can think to do it is to have some inline CSS in the head of the page like so:
我能想到的唯一方法是在页面的头部添加一些内联 CSS,如下所示:
<style type="text/css">
@media only screen and (min-width: 680px) {
.hero-image { background-image: url(../images/image.jpg); }
}
</style>
First, can I use media queries in inline CSS?
首先,我可以在内联 CSS 中使用媒体查询吗?
Second, will this avoid downloading the image on mobiles?
其次,这会避免在手机上下载图像吗?
Third, is there a better way?
第三,有没有更好的办法?
Thanks
谢谢
采纳答案by Niet the Dark Absol
Yes, you may use media queries in a <style>
tag. The image is only loaded if the CSS requires it to be, so if nothing matches the selector then it won't bother loading the image.
是的,您可以在<style>
标签中使用媒体查询。图像仅在 CSS 需要时才加载,因此如果没有与选择器匹配的内容,则不会加载图像。
It would probably be better to include the media query in your external CSS file, though. There's no reason to include it inlline.
不过,最好在您的外部 CSS 文件中包含媒体查询。没有理由将其内联。
回答by Natalya Hoota
No, it appears that you cannot inline @media tags:
不,您似乎无法内联 @media 标签:
Please refer to this: Is it possible to put CSS @media rules inline?
回答by Dave Kanter
You might have better luck with a two-step media query, one that begins in CSS but ends in jQuery. Label your divs with an ID so jQuery can find them. The process is explained in detail here: http://www.fourfront.us/blog/jquery-window-width-and-media-queries
使用两步媒体查询可能会更好,一个以 CSS 开始但以 jQuery 结束。用 ID 标记您的 div,以便 jQuery 可以找到它们。这里详细解释了这个过程:http: //www.fourfront.us/blog/jquery-window-width-and-media-queries