Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Image depending on Mobile or Desktop HTML & CSS

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.

like image 836
Andre Korosh Kordasti Avatar asked Jul 10 '26 06:07

Andre Korosh Kordasti


2 Answers

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.

like image 68
Henrik Karlsson Avatar answered Jul 11 '26 20:07

Henrik Karlsson


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;}
}
like image 28
WebbySmart Avatar answered Jul 11 '26 20:07

WebbySmart