17

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

famousgarkin
  • 13,687
  • 5
  • 58
  • 74
GusRuss89
  • 1,314
  • 2
  • 13
  • 20

3 Answers3

8

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.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 7
    Thanks. The reason to include it inline is that it needs to be output by the CMS (there will be a unique hero image per page). – GusRuss89 Oct 16 '12 at 23:25
  • I used the similar way to achieve
     background-image: url("{{ $resource_path }}/pictures/btn_menu_show.png") 
    – windmaomao Aug 13 '14 at 18:22
  • @NiettheDarkAbsol You say there's no reason to include it inline but that isn't true. When you have dynamically generated content such as pulling data and images from a database on the fly you have to use internal css to style the content if it is all different. For example, I have an event calendar that is generated from a database on my server. When an event is added to the calendar it creates a page for the event. Because I want the event image to look right on different devices, there are different files referenced in the db. I have to use internal css to define my media query for the page – Angeliss44 Nov 23 '19 at 01:37
5

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

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

Community
  • 1
  • 1
Natalya Hoota
  • 79
  • 1
  • 1
  • 2
    Although the wording on the original question (at least as of today) does state "inline", the code OP gives shows that they are asking about putting media queries internally, not inline. Common mistake, I make it about once a week. =) – xtoq Apr 15 '16 at 16:16
1

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

Raydot
  • 1,458
  • 1
  • 23
  • 38