Search code examples
cssmedia-queries

Progressively Loading Images with Media Queries


If I opened this on a screen 800px wide, would both the small and big jpg be loaded? or is the browser intelligent enough to ignore the smaller image?

@media screen and (min-width: 480px) {
    div {
        background-image: url(images/small.jpg);
    }
}

@media screen and (min-width: 600px) {
    div {
        background-image: url(images/big.jpg);
    }   
}

Solution

  • Since both media queries will be fulfilled and both rules use the same selector, the second div rule will take precedence, and only big.jpg will be loaded for any div. Once you resize the browser window until the second rule no longer applies, it should go ahead and load small.jpg.

    I made a quick test page with your CSS. Firebug's Net panel verified that big.jpg was being loaded at my usual browser size, and small.jpg only loaded once I made my browser window narrow enough.