htmlcssmobilemedia-queries

How to specify a different image in CSS depending if the user visits on a desktop or a mobile browser


Just a question about CSS for mobile devices,

I have an image that is 1260px wide on my website and when I look at it on the phone it distorts the web site as the rest of the web site is based on a 960px layout.

I have made these images to be now 960px wide for the mobile device but how do I specify in CSS that if it is a mobile use mobile optimized image instead of the one on the regular web site.

So basically if a user goes on the web site on a desktop computer it will show the 1260px image, and if they visit the web site on a mobile it will display the 960px image.

Any ideas?


Solution

  • Im not sure if you want JS, i decided to answer your question if you want CSS3, try this:

    HTML:

    <img src="image.jpg"
         data-src-960px="image-960px.jpg"
         data-src-1260px="image-1260px.jpg"
         alt="">
    

    CSS:

     @media (min-device-width:320px) {
            img[data-src-960px] {
                content: attr(data-src-960px, url);
            }
        }
    
        @media (min-device-width:960px) {
            img[data-src-1260px] {
                content: attr(data-src-1260px, url);
            }
        }
    

    jQuery version:

     $(document).ready(function() {
    
     function imageresize() {
     var contentwidth = $('#content').width();
     if ((contentwidth) < '960'){
     $('.imageclass').attr('src','image-960px.jpg');
     } else {
     $('.imageclass').attr('src','image-1260px.jpg');
     }
     }
    
     imageresize();//Activates when document first loads    
    
     $(window).bind("resize", function(){
     imageresize();
     });
    
     });