@DvD's answer already answers your question. But as this is a very broad subject and discussed (including I'm very interested in a standard solution) I'll leave an alternative that I hope will soon be adapted to all browsers.
The tag <picture>
of html5
This new tag allows us to treat images in the same way we treat the <audio>
tag, where we can put several formats to work on different types of browsers.
In it, we can use the media
attribute with the same syntax as when we use @media-queries
in CSS to display an image relative to screen size.
See this example (resize the screen) also in Jsfiddle :
picture, img {
width: 100%;
height: auto;
}
<picture>
<source srcset="https://vidanimal.com.br/wp-content/uploads/papillon.jpg" media="(max-width: 700px)" alt="Pequeno">
<source srcset="https://www.blupet.com.br/uploads/pets/26984/2698418092017185025000000.jpg" media="(max-width: 1024px)" alt="Medio">
<img srcset="https://www.ultracurioso.com.br/wp-content/uploads/2015/07/sao-bernardo.jpg" alt="Grande (imagem fallback padrão)">
</picture>
When resizing the screen will be shown the image corresponding to the @media-querie
you defined in the media
attribute, in it you can use the attributes max-width
, min-width
, max-height
, min-height
, orientation
among others that conform to the syntax of @media-queries
.
In the test I did in Chrome (v61), FireFox (v55) and Opera (v48), in IE11 I had to add one more line in the <img>
default tag with a src
to work, it looks like this:
<img src="https://www.ultracurioso.com.br/wp-content/uploads/2015/07/sao-bernardo.jpg"srcset="https://www.ultracurioso.com.br/wp-content/uploads/2015/07/sao-bernardo.jpg" alt="Grande (imagem fallback padrão)">
So it worked in other browsers that I quoted without conflict.
You can see the support for this tag in the Can I Use and use it if you see it calming, and still if you are not sure there is a JS plugin called Picturefill that promises to be crossbrowser
and uses the same syntax as it did.
The answer is a bit big, but if anyone has a suggestion for editing just comment.
Sources: Webdesign.tutsplus , Google;) and Smashing Magazine .