Search code examples
cssmedia-queries

How does Media Queries Reacts


I want to know how does media queries reacts.

For example, I have place an image of size 1400px by 500px for basic media and another image of size 450px by 200px for mobile device.

I am calling it in the same html page using media queries. I want to display small image when user open it in mobile device.

If I call two CSS for same image (ie. changes background using css as per media), will my big image be loaded in mobile device? Or it will simply load the small image ignoring larger one? I have put the main CSS before the mobile CSS. I think big image must have been loaded. If so, then my site will work slowly in mobile devices.

What's your view?


Solution

  • No, the big picture will not be displayed on mobile devices, as long as you insert it into a media query that excludes it. But it will be downloaded if you organize your CSS this way:

    /* FIRST DECLARATION:
        BROWSER STARTS DOWNLOADING THE IMAGE */
    .my-img-class{
        background:url(my-large-image.jpg);
    }
    
    /* SECOND DECLARATION:
        THE RULE ABOVE IS OVERWRITTEN, SO THIS IMAGE WILL BE DOWNLOADED TOO */
    @media only screen and (max-width: 600px) {
        .my-img-class{
            background:url(my-small-image.jpg);
        }
    }
    

    To prevent mobile devices to keep downloading the large image, you should wrap both rules into a media query.

    Here's an example.

    @media only screen and (max-width: 600px) {
        .my-img-class{
            background:url(my-small-image.jpg);
        }
    }
    

    The code above will be interpreted only by devices with screens smaller then 600px.

    @media screen and (min-width: 601px) {
        .my-img-class{
            background:url(my-large-image.jpg);
        }
    }
    

    The code above will be interpreted only by devices with screens larger then 600px.


    You can use different approaches to prevent the downloading of both images.

    Much depends on the target of your site. If the mobile version is the most widely used, you should start planning that, then add gradually, through media queries, the content for the desktop version.


    Here are some resources that you'll find usefuls: