Search code examples
htmlcssmedia-queries

Use media query inline style


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


Solution

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