@media queries and image swapping

Aarati Akkapeddi picture Aarati Akkapeddi · Jan 9, 2015 · Viewed 61k times · Source

I want the image in my site to completely change when the browser is resized.

I've been using media-queries, but I can't seem to get it right. Any thoughts/tips?

Answer

jmore009 picture jmore009 · Jan 9, 2015

In the future please add code you've tried.

if it's an image tag you can use a class. Hide the second image on page load and show + hide image 1 at a certain screen size like so:

HTML

<img src="image.jpg" class="image1"/>
<img src="image.jpg" class="image2"/>

CSS

.image2{
   display: none;
}

@media only screen and (max-width: 500px){ //some value
   .image1{
     display: none;
   }

   .image2{
     display: block;
   }
}

EXAMPLE 1 - SHRINK BROWSER

OR

If it's a background-image you can simply swap the image:

HTML

<div class="example"></div>

CSS

.example{
   background-image: url("example.jpg");
}

@media only screen and (max-width: 500px){ //some value

   .example{
      background-image: url("example2.jpg");
   }
}

EXAMPLE 2 - SHRINK BROWSER