Changing image src depending on screen size

This one is working for me. I don't know if you're familiar with this tag but it doesn't even need CSS.

<picture>
    <source media="(min-width: 900px)" srcset="BigImage.png">
    <source media="(min-width: 480px)" srcset="MediumImage.png">
    <img src="OtherImage.png" alt="IfItDoesntMatchAnyMedia">
</picture>

In this case "BigImage" Would show when the device width is more than 900px. "MediumImage" when its's more than 480px and "OtherImage" If It's less than 480px. If you had "max-width: 900px" instead of min-width, it would also show when the width is more than 900px.

Hope it helps!


We already have feature to load images based on screen sizes. You don't need CSS Media query for that. because to load dynamic images coming from database it's not feasible for you to create media query on the fly.

SOLUTION :

Use srcset attribute

EXAMPLE :

<img src="small.jpg" srcset="medium.jpg 1000w, large.jpg 2000w" alt="yah">

in the above code all you need to define is width size next to the images separated by commas.

Hope it helps :-)


<picture>
  <source media="(max-width: 799px)" srcset="elva-480w-close-portrait.jpg">
  <source media="(min-width: 800px)" srcset="elva-800w.jpg">
  <img src="elva-800w.jpg" alt="Chris standing up holding his daughter Elva">
</picture>

Let's fix this, with <picture>! Like <video> and <audio>, The <picture> element is a wrapper containing several <source> elements that provide several different sources for the browser to choose between, followed by the all-important <img> element.


this is working for me:

#main-img {
  
  height: 250px;
  width:100%
} 

@media screen and (max-width: 767px) {   
    #main-img{
    	background-image: url(http://subtlepatterns.com/patterns/dark_embroidery.png);
    } 
}

@media screen and (min-width: 768px) {      
    #main-img{      
    	background-image: url(http://subtlepatterns.com/patterns/dark_embroidery.png);
    } 
} 
@media (min-width: 992px) {      
      #main-img{        
          background-image: url(http://subtlepatterns.com/patterns/paisley.png);
      } 
}
@media (min-width: 1200px) {    
     #main-img{         
         background-image: url(http://subtlepatterns.com/patterns/paisley.png);
     } 
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<div class="container">
    <div id="main-img" />
</div>