0

I want to load image on web page based on img element size not screen/viewport size.

For example, I have two images like res-100px.png with 100px resolution and res-200px.png with 200px resolution.

If img width less than or equal to 100px load res-100px.png image. If img width greater than 100px load res-200px.png image.

So, Is it possible to solve this with just HTML5 and CSS3 without JS. If possible please provide some example.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Temüjin
  • 15,371
  • 8
  • 35
  • 57
  • 1
    Maybe add the relevant code, both html and css, tell us do you use some framework? It is not 100% clear what you want to do. – skobaljic Feb 20 '17 at 17:06
  • @skobaljic for example see *Akxe* answer. That loads image based on viewport size. I want to load image based `img` element size. – Temüjin Feb 20 '17 at 17:09

2 Answers2

0

There is a special element just for this case. See picture

​<picture>
 <source srcset="mdn-logo.svg" type="image/svg+xml">
 <!-- Load SVG preferrably -->

 <source srcset="large.jpg  1024w,
     medium.jpg 640w,
     small.jpg  320w" sizes="33.3vw">
 <!-- Load image for size(s) -->


 <source srcset="logo-big.png" media="(min-width: 600px)">
 <source srcset="logo-small.png" media="(max-width: 600px)">
 <!-- Load image for size(s) -->

 <img src="mdn-logo.jpg" alt="MDN">
 <!-- Display fallback image (not it will probably be IE9 so you can include thebig variant) -->
</picture>

It can detect if a type is displayable, for example if your image can be seen as SVG, or it can switch based on display size. It also have nice fallback in form of img, that is not rendered by newer browsers.

Akxe
  • 9,694
  • 3
  • 36
  • 71
  • See `media="(min-width: 600px)"` on your example. It loads image based on viewport. – Temüjin Feb 20 '17 at 17:08
  • In the question title it clearly says `based on image size not screen size`. – skobaljic Feb 20 '17 at 17:09
  • You would have to use JS for anything else than this, this is the most responsive thing I am aware of. There is that option for SVG, but if your image is raster, rather than vectors, it won't be an option for you either. – Akxe Feb 20 '17 at 17:13
  • The srcset is the best HTML5 way to go about it, it will tell the browser, what image is what size, and it will chose based on its preferences. – Akxe Feb 20 '17 at 17:20
0

Well you could try jQuery to get the width of each image and add a class depending on the criteria you want, and then just append an the image or whatever you need...

 $('img').addClass(function() {
    if ( this.height > 200 ) {
       return 'show-res-200px';
    } else {
       return 'show-res-100px';
    }
});

Check this JSFiddle

TylerH
  • 20,799
  • 66
  • 75
  • 101