Can I use a media query in internal CSS, and will it avoid loading the background images I define?

余生长醉 提交于 2020-01-03 06:48:13

问题


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.

The only way I can think to do it is to have some inline CSS in the head of the page like so:

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

Second, will this avoid downloading the image on mobiles?

Third, is there a better way?

Thanks


回答1:


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.

It would probably be better to include the media query in your external CSS file, though. There's no reason to include it inlline.




回答2:


No, it appears that you cannot inline @media tags:

Please refer to this: Is it possible to put CSS @media rules inline?




回答3:


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



来源:https://stackoverflow.com/questions/12906913/can-i-use-a-media-query-in-internal-css-and-will-it-avoid-loading-the-backgroun

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!