Use media query inline style [duplicate]

2019-01-26 03:59发布

问题:

This question already has an answer here:

  • Is it possible to put CSS @media rules inline? 11 answers

I know it sounds ridiculous, but can I use a css media query in an inline style? The reason is I'm echoing a background in PHP and need to use a retina size image if the device is retina.

ie: <div style="background:url(normal.png); <- need to add style for retina device

回答1:

Not within an inline style declaration as far as I know.

However, if you're echoing from within PHP and really can't access the stylesheet I would suggest echoing an inline <style /> element with the media query and using a class for the div.

i.e.

<style type="text/css">
    .bg {
        background: url(background.jpg);
    }
    @media only screen and (max-device-width: 480px) { /* Change to whatever media query you require */
        .bg {
             background: url(background_highres.jpg);
        }
    }

</style>
<div class="bg">...</div>