Search code examples
csshtmlmedia-queries

Media Query: Image src property change using css


I'm developing an HTML5 app for Android, iPhone and Windows phone and I'm using media queries to display different image files depending on the screen width.

If I display the image using the CSS background-image property, I could change the image file using different CSS classes according to the media query value. But I'm unable to change the image if it is displayed using the img tag.

Is there any way to change the image source associated with the img tag using CSS media queries?


Solution

  • Use a sprite sheet and alter the background-position of a <div> or similar (which will replace an <img> on the page) to sample a new portion of the sprite depending on your media query criteria.

    Example:

    HTML:

    <div></div>
    

    CSS:

    div
    {
        width: 100px;
        height: 100px;
        background: url(http://martywallace.com/view/textures/photo/terraria.jpg) no-repeat;
    }
    
    @media all and (max-width: 1000px)
    {
        div
        {
            background-position: -20px -50px;
        }
    }