Is it possible to put CSS @media rules inline?

Dancer picture Dancer · Mar 21, 2012 · Viewed 419.4k times · Source

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?

Answer

BoltClock picture BoltClock · Mar 21, 2012

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); }
}