Changing Image depending on Mobile or Desktop HTML & CSS

29,420

Solution 1

Another trick would be to have two img tags, and hide one depending on the device.

HTML

<img id="img1" src="images/arts/IMG_1447.png" alt="">
<img id="img2" src="images/arts/IMG_1447m.png" alt="">

CSS

#img1 {display:block;}
#img2 {display:none}

@media all and (max-width: 499px) {
    #img1 {display: none;}
    #img2 {display: block;}
}

Solution 2

If you want to live in the future, the <picture> element is the way to go. It still has really bad browser support (only blink based browsers, and firefox beta as of now). The good news is that it falls back to a dumb <img> tag, so no harm done except a little slower loading if it's not supported.

Alright, so how does it work?

Most of this example is taken from html5rocks with some modifications

A picture element looks like this:

<picture>
  <source 
    media="(min-width: 650px)"
    srcset="images/kitten-stretching.png">
  <source 
    media="(min-width: 465px)"
    srcset="images/kitten-sitting.png">
  <img 
    src="images/kitten-curled.png" 
    alt="a cute kitten">
</picture>

Try the example for yourself at http://googlechrome.github.io/samples/picture-element/, simply resize the width of the browser to see the kitten change.

The cool thing about the picture element is that it allows you to specify media queries to each of the <source> elements. The last <img> is shown if no source is matched, or if the picture element is unsupported.

Share:
29,420
Andre Korosh Kordasti
Author by

Andre Korosh Kordasti

Updated on June 01, 2020

Comments

  • Andre Korosh Kordasti
    Andre Korosh Kordasti almost 4 years

    So im trying to change the image depending on if the user is on mobile or desktop version.

    I have two different images, the one with an "m" in the end is a mini-version which is for desktop, and the other is for mobile. I cant get it to work though.

    Here's some code:

    HTML (Using Razor, so C# code works):

    <img id="ifMobile1" src="images/arts/IMG_1447m.png" alt="">
    

    CSS:

    #ifMobile1 {
        background-image: url(/images/arts/IMG_1447m.png)
    }
    
    @media all and (max-width: 499px) {
        #ifMobile1 {
            background-image: url(/images/arts/IMG_1447.png)
        }
    }
    

    Help me please.